google-app-enginedatastorelocal-datastore

Running Datastore query with two equality filter on different props


I have a datastore query that filters on different props by equality, after debugging the query, i found that the 2nd filter only applies, the first one doesn't be taken by the query.

Here's the query:

Query<Entity> query = Query.newEntityQueryBuilder().setKind("locations")
    .setFilter(StructuredQuery.PropertyFilter.eq("country",countryCode))
    .setFilter(StructuredQuery.PropertyFilter.eq("type",locationTypeCode))
    .build();

As far as i know, when filter on different props, it should work, but in my case doesn't apply?


Solution

  • I tried doing this recently myself, and from what I saw, adding multiple filters onto a query just overwrote the filter. Composite filters solve that problem. There's a section in the query documentation that may be useful: https://cloud.google.com/appengine/docs/standard/java/datastore/queries#query_interface_example

    // Use CompositeFilter to combine multiple filters
    CompositeFilter heightRangeFilter =
        CompositeFilterOperator.and(heightMinFilter, heightMaxFilter);
    
    // Use class Query to assemble a query
    Query q = new Query("Person").setFilter(heightRangeFilter);