|
| 1 | +/* |
| 2 | + * Copyright 2023 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.datastore.filters; |
| 18 | + |
| 19 | +// sample-metadata: |
| 20 | +// title: Create a union between two filters |
| 21 | +// description: Create a union between two filters (logical OR operator) |
| 22 | + |
| 23 | +// [START datastore_query_filter_or] |
| 24 | +import com.google.cloud.datastore.Datastore; |
| 25 | +import com.google.cloud.datastore.DatastoreOptions; |
| 26 | +import com.google.cloud.datastore.Entity; |
| 27 | +import com.google.cloud.datastore.Query; |
| 28 | +import com.google.cloud.datastore.QueryResults; |
| 29 | +import com.google.cloud.datastore.StructuredQuery.CompositeFilter; |
| 30 | +import com.google.cloud.datastore.StructuredQuery.Filter; |
| 31 | +import com.google.cloud.datastore.StructuredQuery.PropertyFilter; |
| 32 | + |
| 33 | +public class OrFilterQuery { |
| 34 | + public static void invoke() throws Exception { |
| 35 | + |
| 36 | + // Instantiates a client |
| 37 | + Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); |
| 38 | + String propertyName = "description"; |
| 39 | + |
| 40 | + // Create the two filters |
| 41 | + Filter orFilter = |
| 42 | + CompositeFilter.or( |
| 43 | + PropertyFilter.eq(propertyName, "Feed cats"), |
| 44 | + PropertyFilter.eq(propertyName, "Buy milk")); |
| 45 | + |
| 46 | + // Build the query |
| 47 | + Query<Entity> query = Query.newEntityQueryBuilder().setKind("Task").setFilter(orFilter).build(); |
| 48 | + |
| 49 | + // Get the results back from Datastore |
| 50 | + QueryResults<Entity> results = datastore.run(query); |
| 51 | + |
| 52 | + if (!results.hasNext()) { |
| 53 | + throw new Exception("query yielded no results"); |
| 54 | + } |
| 55 | + |
| 56 | + while (results.hasNext()) { |
| 57 | + Entity entity = results.next(); |
| 58 | + System.out.printf("Entity: %s%n", entity); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | +// [END datastore_query_filter_or] |
0 commit comments