com.google.appengine.api.search.QueryOptions Java Examples

The following examples show how to use com.google.appengine.api.search.QueryOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearchAsyncQuery() throws ExecutionException, InterruptedException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    Index index = createIndex(indexName, docId);

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
            .setIndexNamePrefix(indexName)
            .build();
    GetResponse<Index> response = searchService.getIndexes(request);
    List<Index> listIndexes = response.getResults();

    for (Index oneIndex : listIndexes) {
        QueryOptions.Builder optionBuilder = QueryOptions.newBuilder();
        optionBuilder.setLimit(10);
        Query.Builder queryBuilder = Query.newBuilder().setOptions(optionBuilder.build());
        Future<Results<ScoredDocument>> Fres = oneIndex.searchAsync(queryBuilder.build(""));

        Iterator<ScoredDocument> it = Fres.get().iterator();
        assertEquals(docId + "1", it.next().getId());
        assertEquals(docId + "2", it.next().getId());
        sync();
    }
}
 
Example #2
Source File: SearchQuery.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
protected SearchQuery(List<InstructorAttributes> instructors, String queryString) {
    options = QueryOptions.newBuilder()
            .setLimit(20)
            .build();
    visibilityQueryString = instructors == null ? "" : prepareVisibilityQueryString(instructors);
    setTextFilter(Const.SearchDocumentField.SEARCHABLE_TEXT, queryString);
}
 
Example #3
Source File: FeedbackResponseCommentSearchQuery.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
public FeedbackResponseCommentSearchQuery(List<InstructorAttributes> instructors, String queryString) {
    super(instructors, queryString);
    options = QueryOptions.newBuilder()
            .setLimit(20)
            .setFieldsToReturn(Const.SearchDocumentField.COURSE_ID,
                    Const.SearchDocumentField.FEEDBACK_RESPONSE_GIVER_NAME,
                    Const.SearchDocumentField.FEEDBACK_RESPONSE_RECEIVER_NAME,
                    Const.SearchDocumentField.FEEDBACK_RESPONSE_COMMENT_GIVER_NAME)
            .build();
}
 
Example #4
Source File: StudentSearchQuery.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
public StudentSearchQuery(List<InstructorAttributes> instructors, String queryString) {
    super(instructors, queryString);
    options = QueryOptions.newBuilder()
            .setLimit(20)
            .setFieldsToReturn(Const.SearchDocumentField.COURSE_ID)
            .build();
}
 
Example #5
Source File: StudentSearchQuery.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This constructor should be used by admin only since the searching does not restrict the
 * visibility according to the logged-in user's google ID. This is used by amdin to
 * search students in the whole system.
 */
public StudentSearchQuery(String queryString) {
    super(queryString);
    options = QueryOptions.newBuilder()
            .setLimit(20)
            .setReturningIdsOnly(true)
            .build();
}
 
Example #6
Source File: InstructorSearchQuery.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This constructor should be used by admin only since the searching does not restrict the
 * visibility according to the logged-in user's google ID. This is used by amdin to
 * search instructors in the whole system.
 */
public InstructorSearchQuery(String queryString) {
    super(queryString);
    options = QueryOptions.newBuilder()
            .setLimit(20)
            .setReturningIdsOnly(true)
            .build();
}
 
Example #7
Source File: SearchTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected Results<ScoredDocument> searchDocs(Index index, String query, int limit) {
    if (limit > 0) {
        QueryOptions.Builder optionBuilder = QueryOptions.newBuilder();
        optionBuilder.setLimit(limit);
        Query.Builder queryBuilder = Query.newBuilder().setOptions(optionBuilder.build());
        return index.search(queryBuilder.build(query));
    } else {
        return index.search(query);
    }
}
 
Example #8
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortOptions() {
    for (SortExpression.SortDirection direction : SortExpression.SortDirection.values()) {
        SortExpression sortExpression = SortExpression.newBuilder()
            .setExpression("numfield")
            .setDirection(direction)
            .setDefaultValueNumeric(9999)
            .build();
        SortOptions sortOptions = SortOptions.newBuilder()
            .addSortExpression(sortExpression)
            .build();
        QueryOptions options = QueryOptions.newBuilder()
            .setFieldsToReturn("numfield", "datefield")
            .setSortOptions(sortOptions)
            .build();
        Query.Builder queryBuilder = Query.newBuilder().setOptions(options);
        Results<ScoredDocument> results = index.search(queryBuilder.build(""));

        double pre = -9999;
        if (direction.equals(SortExpression.SortDirection.DESCENDING)) {
            pre = 9999;
        }
        for (ScoredDocument doc : results) {
            assertEquals(2, doc.getFieldNames().size());
            for (Field numField : doc.getFields("numfield")) {
                if (direction.equals(SortExpression.SortDirection.DESCENDING)) {
                    assertTrue(pre > numField.getNumber());
                } else {
                    assertTrue(pre < numField.getNumber());
                }
                pre = numField.getNumber();
            }
        }
    }
}
 
Example #9
Source File: PlacesHelper.java    From MobileShoppingAssistant-sample with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the nearest places to the location of the user.
 * @param location the location of the user.
 * @param distanceInMeters the maximum distance to the user.
 * @param resultCount the maximum number of places returned.
 * @return List of up to resultCount places in the datastore ordered by
 *      the distance to the location parameter and less than
 *      distanceInMeters meters to the location parameter.
 */
public static List<PlaceInfo> getPlaces(final GeoPt location,
        final long distanceInMeters, final int resultCount) {

    // Optional: use memcache

    String geoPoint = "geopoint(" + location.getLatitude() + ", " + location
            .getLongitude()
            + ")";
    String locExpr = "distance(place_location, " + geoPoint + ")";

    // Build the SortOptions with 2 sort keys
    SortOptions sortOptions = SortOptions.newBuilder()
            .addSortExpression(SortExpression.newBuilder()
                    .setExpression(locExpr)
                    .setDirection(SortExpression.SortDirection.ASCENDING)
                    .setDefaultValueNumeric(distanceInMeters + 1))
            .setLimit(resultCount)
            .build();
    // Build the QueryOptions
    QueryOptions options = QueryOptions.newBuilder()
            .setSortOptions(sortOptions)
            .build();
    // Query string
    String searchQuery = "distance(place_location, " + geoPoint + ") < "
            + distanceInMeters;

    Query query = Query.newBuilder().setOptions(options).build(searchQuery);

    Results<ScoredDocument> results = getIndex().search(query);

    if (results.getNumberFound() == 0) {
        // geo-location doesn't work under dev_server
        if (environment.value() == Development) {
            // return all documents
            results = getIndex().search("value > 0");
        }
    }

    List<PlaceInfo> places = new ArrayList<>();

    for (ScoredDocument document : results) {
        if (places.size() >= resultCount) {
            break;
        }

        GeoPoint p = document.getOnlyField("place_location").getGeoPoint();

        PlaceInfo place = new PlaceInfo();
        place.setPlaceId(Long.valueOf(document.getOnlyField("id")
                .getText()));
        place.setName(document.getOnlyField("name").getText());
        place.setAddress(document.getOnlyField("address").getText());

        place.setLocation(new GeoPt((float) p.getLatitude(),
                (float) p.getLongitude()));

        // GeoPoints are not implemented on dev server and latitude and
        // longitude are set to zero
        // But since those are doubles let's play safe
        // and use double comparison with epsilon set to EPSILON
        if (Math.abs(p.getLatitude()) <= EPSILON
                && Math.abs(p.getLongitude()) <= EPSILON) {
            // set a fake distance of 5+ km
            place.setDistanceInKilometers(FAKE_DISTANCE_FOR_DEV + places
                    .size());
        } else {
            double distance = distanceInMeters / METERS_IN_KILOMETER;
            try {
                distance = getDistanceInKm(
                        p.getLatitude(), p.getLongitude(),
                        location.getLatitude(),
                        location.getLongitude());
            } catch (Exception e) {
                LOG.warning("Exception when calculating a distance: " + e
                        .getMessage());
            }

            place.setDistanceInKilometers(distance);
        }

        places.add(place);
    }
    return places;
}
 
Example #10
Source File: SearchOptionServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private Results<ScoredDocument> doSearch() {
  String indexName = SEARCH_INDEX;
  // [START search_with_options]
  try {
    // Build the SortOptions with 2 sort keys
    SortOptions sortOptions =
        SortOptions.newBuilder()
            .addSortExpression(
                SortExpression.newBuilder()
                    .setExpression("price")
                    .setDirection(SortExpression.SortDirection.DESCENDING)
                    .setDefaultValueNumeric(0))
            .addSortExpression(
                SortExpression.newBuilder()
                    .setExpression("brand")
                    .setDirection(SortExpression.SortDirection.DESCENDING)
                    .setDefaultValue(""))
            .setLimit(1000)
            .build();

    // Build the QueryOptions
    QueryOptions options =
        QueryOptions.newBuilder()
            .setLimit(25)
            .setFieldsToReturn("model", "price", "description")
            .setSortOptions(sortOptions)
            .build();

    // A query string
    String queryString = "product: coffee roaster AND price < 500";

    //  Build the Query and run the search
    Query query = Query.newBuilder().setOptions(options).build(queryString);
    IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build();
    Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
    Results<ScoredDocument> result = index.search(query);
    return result;
  } catch (SearchException e) {
    // handle exception...
  }
  // [END search_with_options]
  return null;
}
 
Example #11
Source File: PlacesHelper.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 4 votes vote down vote up
static List<PlaceInfo> getPlaces(GeoPt location, long distanceInMeters, int resultCount) {

    // TODO(user): Use memcache

    String geoPoint = "geopoint(" + location.getLatitude() + ", " + location.getLongitude() + ")";

    String query = "distance(place_location, " + geoPoint + ") < " + distanceInMeters;
    String locExpr = "distance(place_location, " + geoPoint + ")";

    SortExpression sortExpr = SortExpression.newBuilder()
        .setExpression(locExpr)
        .setDirection(SortExpression.SortDirection.ASCENDING)
        .setDefaultValueNumeric(distanceInMeters + 1)
        .build();
    Query searchQuery = Query.newBuilder().setOptions(QueryOptions.newBuilder()
        .setSortOptions(SortOptions.newBuilder().addSortExpression(sortExpr))).build(query);
    Results<ScoredDocument> results = getIndex().search(searchQuery);

    if (results.getNumberFound() == 0) {
      // geo-location doesn't work under dev_server
      if (environment.value() == Development) {
        // return all documents
        results = getIndex().search("value > 0");
      }
    }

    List<PlaceInfo> places = new ArrayList<PlaceInfo>();

    for (ScoredDocument document : results) {
      if (places.size() >= resultCount) {
        break;
      }

      GeoPoint p = document.getOnlyField("place_location").getGeoPoint();

      PlaceInfo place = new PlaceInfo();
      place.setplaceID(document.getOnlyField("id").getText());
      place.setName(document.getOnlyField("name").getText());
      place.setAddress(document.getOnlyField("address").getText());

      place.setLocation(new GeoPt((float) p.getLatitude(), (float) p.getLongitude()));

      // GeoPoints are not implemented on dev server and latitude and longitude are set to zero
      // But since those are doubles let's play safe
      // and use double comparison with epsilon set to 0.0001
      if (Math.abs(p.getLatitude()) <= 0.0001 && Math.abs(p.getLongitude()) <= 0.0001) {
        // set a fake distance of 5+ km
        place.setDistanceInKilometers(5 + places.size());
      } else {
        double distance = distanceInMeters / 1000;
        try {
          distance = getDistanceInKm(
              p.getLatitude(), p.getLongitude(), location.getLatitude(), location.getLongitude());
        } catch (Exception e) {
          log.warning("Exception when calculating a distance: " + e.getMessage());
        }

        place.setDistanceInKilometers(distance);
      }

      places.add(place);
    }

    return places;
  }