Java Code Examples for com.google.appengine.api.datastore.Query#addSort()

The following examples show how to use com.google.appengine.api.datastore.Query#addSort() . 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: MetadataPropertiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void printPropertyRange(DatastoreService ds, PrintWriter writer) {

    // Start with unrestricted keys-only property query
    Query q = new Query(Entities.PROPERTY_METADATA_KIND).setKeysOnly();

    // Limit range
    q.setFilter(
        CompositeFilterOperator.and(
            new FilterPredicate(
                Entity.KEY_RESERVED_PROPERTY,
                Query.FilterOperator.GREATER_THAN_OR_EQUAL,
                Entities.createPropertyKey("Employee", "salary")),
            new FilterPredicate(
                Entity.KEY_RESERVED_PROPERTY,
                Query.FilterOperator.LESS_THAN_OR_EQUAL,
                Entities.createPropertyKey("Manager", "salary"))));
    q.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);

    // Print query results
    for (Entity e : ds.prepare(q).asIterable()) {
      writer.println(e.getKey().getParent().getName() + ": " + e.getKey().getName());
    }
  }
 
Example 2
Source File: ProjectionTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void projectionQuery_grouping_filtersDuplicates() {
  putTestData("some duplicate", 0L);
  putTestData("some duplicate", 0L);
  putTestData("too big", 1L);

  // [START grouping]
  Query q = new Query("TestKind");
  q.addProjection(new PropertyProjection("A", String.class));
  q.addProjection(new PropertyProjection("B", Long.class));
  q.setDistinct(true);
  q.setFilter(Query.FilterOperator.LESS_THAN.of("B", 1L));
  q.addSort("B", Query.SortDirection.DESCENDING);
  q.addSort("A");
  // [END grouping]

  List<Entity> entities = datastore.prepare(q).asList(FetchOptions.Builder.withLimit(5));
  assertThat(entities).hasSize(1);
  Entity entity = entities.get(0);
  assertWithMessage("entity.A")
      .that((String) entity.getProperty("A"))
      .isEqualTo("some duplicate");
  assertWithMessage("entity.B").that((long) entity.getProperty("B")).isEqualTo(0L);
}
 
Example 3
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private static <T extends TempData> List<T> getAllTempData(Class<T> type, boolean unreadOnly) {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        String kind = getKind(type);
        Query query = new Query(kind);
        if (unreadOnly) {
            query.setFilter(new Query.FilterPredicate(TEMP_DATA_READ_PROPERTY, Query.FilterOperator.EQUAL, false));
        } else {
            query.addSort("timestamp", Query.SortDirection.ASCENDING);
        }
        PreparedQuery pq = ds.prepare(query);
        Iterator<Entity> iter = pq.asIterator();
        List<T> result = new ArrayList<>();
        while (iter.hasNext()) {
            Entity entity = iter.next();
            T data = readTempData(type, entity, ds);
            result.add(data);
        }
        return result;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 4
Source File: QueryTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompositeFilter() {
    Query query = new Query(kindName, rootKey);
    Filter filter = Query.CompositeFilterOperator.and(
        Query.FilterOperator.LESS_THAN_OR_EQUAL.of("intData", 40),
        Query.FilterOperator.GREATER_THAN.of("intData", 0));
    query.setFilter(filter);
    query.addSort("intData", Query.SortDirection.DESCENDING);
    List<Entity> es = service.prepare(query).asList(fo);
    assertEquals("check return count", 2, es.size());
    assertEquals("check query filter", filter, query.getFilter());
    assertEquals("check query key only", false, query.isKeysOnly());

    Query.CompositeFilter cf = (Query.CompositeFilter) query.getFilter();
    assertEquals(2, cf.getSubFilters().size());
    assertEquals(Query.CompositeFilterOperator.AND, cf.getOperator());
}
 
Example 5
Source File: CursorTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartEndCursor() {
    int limit = total / testDat.length;
    Query query = new Query(kindName, rootKey);
    query.addSort("name", Query.SortDirection.ASCENDING);
    FetchOptions fetchOption = FetchOptions.Builder.withLimit(limit);
    // fetch 1st page and get cursor1
    QueryResultList<Entity> nextBatch = service.prepare(query)
        .asQueryResultList(fetchOption);
    Cursor cursor1 = Cursor.fromWebSafeString(nextBatch.getCursor().toWebSafeString());
    // fetch 2nd page and get cursor2
    nextBatch = service.prepare(query).asQueryResultList(fetchOption.startCursor(cursor1));
    Cursor cursor2 = Cursor.fromWebSafeString(nextBatch.getCursor().toWebSafeString());
    // cursor1 as start and cursor2 as end and 15 in limit -- -- should return 2nd page.
    checkPage(query, cursor1, cursor2, limit, limit, testDat[1], testDat[1]);
    // cursor1 as start and cursor2 as end and 30 in limit -- should return 2nd page.
    checkPage(query, cursor1, cursor2, 2 * limit, limit, testDat[1], testDat[1]);
    // cursor2 as start and cursor1 as end and 15 in limit -- should not return any.
    checkPage(query, cursor2, cursor1, limit, 0, null, null);
}
 
Example 6
Source File: DistinctTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctSort() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("stringData", String.class));
    query.addProjection(new PropertyProjection("floatData", Float.class));
    query.addSort("stringData", Query.SortDirection.DESCENDING);
    query.setDistinct(true);
    assertEquals(7, service.prepare(query).countEntities(fo));
    assertTrue(query.getDistinct());
    query.addSort("floatData", Query.SortDirection.DESCENDING);
    assertEquals(7, service.prepare(query).countEntities(fo));
}
 
Example 7
Source File: DistinctTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctFilter() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("stringData", String.class));
    query.addProjection(new PropertyProjection("floatData", Float.class));
    query.setFilter(new FilterPredicate("stringData", Query.FilterOperator.NOT_EQUAL, "string1"));
    query.addSort("stringData", Query.SortDirection.DESCENDING);
    query.setDistinct(true);
    assertEquals(5, service.prepare(query).countEntities(fo));
    assertTrue(query.getDistinct());
}
 
Example 8
Source File: BatchTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void testStep2BigAsList() {
    Query q = new Query(kindName, rootKey);
    q.addSort("count", Query.SortDirection.DESCENDING);
    List<Entity> eData = service.prepare(q).asList(fo);
    assertEquals(bigCount, eData.size());
    assertEquals(new Integer(bigCount - 1).longValue(), eData.get(0).getProperty("count"));
}
 
Example 9
Source File: QueryTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testReverse() throws Exception {
    final Query query = new Query(kindName, rootKey);
    query.addSort(Entity.KEY_RESERVED_PROPERTY);
    query.addSort("intData");

    List<Entity> list1 = service.prepare(query).asList(FetchOptions.Builder.withDefaults());
    List<Entity> list2 = service.prepare(query.reverse()).asList(FetchOptions.Builder.withDefaults());

    int size = list1.size();
    Assert.assertEquals(size, list2.size());
    for (int i = 0; i < size; i++) {
        Assert.assertEquals(list1.get(i), list2.get(size - i - 1));
    }
}
 
Example 10
Source File: QueryTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortPredicates() {
    Query query = new Query(kindName, rootKey);
    query.addSort("intData", Query.SortDirection.DESCENDING);
    List<Entity> es = service.prepare(query).asList(fo);
    assertEquals((long) 40, es.get(0).getProperty("intData"));
    List<Query.SortPredicate> qsp = query.getSortPredicates();
    assertEquals("check SortPredicate name", "intData", qsp.get(0).getPropertyName());
    assertEquals("check SortPredicate direction", Query.SortDirection.DESCENDING, qsp.get(0).getDirection());
}
 
Example 11
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected List<Entity> doQuery(String kind, String pName, Class<?> type, boolean indexed) {
    FetchOptions fo = FetchOptions.Builder.withDefaults();
    Query query = new Query(kind, rootKey);
    if (indexed) {
        query.addProjection(new PropertyProjection(pName, type));
        query.addSort(pName);
    }
    return service.prepare(query).asList(fo);
}
 
Example 12
Source File: PhotoManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Photo> getActivePhotos() {
  Query query = new Query(getKind());
  Query.Filter filter = new Query.FilterPredicate(PhotoNoSql.FIELD_NAME_ACTIVE,
      FilterOperator.EQUAL, true);
  query.addSort(PhotoNoSql.FIELD_NAME_UPLOAD_TIME, SortDirection.DESCENDING);
  query.setFilter(filter);
  FetchOptions options = FetchOptions.Builder.withDefaults();
  return queryEntities(query, options);
}
 
Example 13
Source File: CursorTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndCursor() {
    int limit = total / testDat.length;
    Query query = new Query(kindName, rootKey);
    query.addSort("name", Query.SortDirection.ASCENDING);
    // fetch 1st page
    Cursor cursor = checkPage(query, null, null, limit, limit, testDat[0], testDat[0]);
    Cursor decodedCursor = Cursor.fromWebSafeString(cursor.toWebSafeString());
    // fetch 1st page again since using decodedCursor as end cursor
    checkPage(query, null, decodedCursor, limit, limit, testDat[0], testDat[0]);
}
 
Example 14
Source File: DistinctTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctFilter2() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("stringData", String.class));
    query.addProjection(new PropertyProjection("floatData", Float.class));
    query.setFilter(new FilterPredicate("stringData", Query.FilterOperator.GREATER_THAN,
        "string0"));
    query.addSort("stringData", Query.SortDirection.DESCENDING);
    query.addSort("floatData", Query.SortDirection.DESCENDING);
    query.setDistinct(true);
    assertEquals(2, service.prepare(query).countEntities(fo));
    assertTrue(query.getDistinct());
}
 
Example 15
Source File: CommentManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Comment> getComments(Photo photo) {
  Query query = new Query(getKind());
  Query.Filter photoIdFilter =
      new Query.FilterPredicate(CommentNoSql.FIELD_NAME_PHOTO_ID,
          FilterOperator.EQUAL, photo.getId());
  List<Filter> filters = Arrays.asList(photoIdFilter, new Query.FilterPredicate(
      CommentNoSql.FIELD_NAME_PHOTO_OWNER_ID, FilterOperator.EQUAL, photo.getOwnerId()));
  Filter filter = new Query.CompositeFilter(CompositeFilterOperator.AND, filters);
  query.setFilter(filter);
  query.addSort(CommentNoSql.FIELD_NAME_TIMESTAMP, SortDirection.DESCENDING);
  FetchOptions options = FetchOptions.Builder.withDefaults();
  return queryEntities(query, options);
}
 
Example 16
Source File: IndexQueryTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryOrder() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("intData", Integer.class));
    query.addSort("stringData", Query.SortDirection.DESCENDING);
    List<Entity> results = service.prepare(query).asList(fetchOption);
    assertEquals(count, results.size());
    int first = new Integer(results.get(0).getProperty("intData").toString());
    int last = new Integer(results.get(count - 1).getProperty("intData").toString());
    assertTrue(first > last);
}
 
Example 17
Source File: ListTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testStrFilter() {
    Query q = new Query(kindName);
    q.setAncestor(rootKey);
    Query.Filter filter = Query.CompositeFilterOperator.and(
        new FilterPredicate("stringData", Query.FilterOperator.LESS_THAN, "qqq"),
        new FilterPredicate("stringData", Query.FilterOperator.GREATER_THAN, "mmm"));
    q.setFilter(filter);
    q.addSort("stringData", Query.SortDirection.ASCENDING);
    assertEquals(2, service.prepare(q).countEntities(fo));
    List<Entity> elist = service.prepare(q).asList(fo);
    assertEquals(Arrays.asList("abc", "xyz", "mno"), elist.get(0).getProperty("stringData"));
    assertEquals(Arrays.asList("ppp", "iii", "ddd"), elist.get(1).getProperty("stringData"));
}
 
Example 18
Source File: QueryIssuingServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String kind = req.getParameter("kind");
  Query query = new Query(kind);
  query.addFilter("p1", Query.FilterOperator.EQUAL, "a");
  query.addSort("p2", Query.SortDirection.DESCENDING);
  DatastoreServiceFactory.getDatastoreService().prepare(query).asSingleEntity();
}
 
Example 19
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
protected void doSort(String kind, String pName, Object fDat, Query.SortDirection direction) {
    Query query = new Query(kind, rootKey);
    query.addSort(pName, direction);
    Object[] result = getResult(query, pName);
    assertEquals(fDat.toString(), result[0].toString());
}
 
Example 20
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
protected void doSort(String kind, String pName, int expDat, Query.SortDirection direction) {
    Query query = new Query(kind, rootKey);
    query.addSort(pName, direction);
    Object[] result = getResult(query, pName);
    assertEquals(expDat, result.length);
}