두 필터의 합집합 만들기(OR 연산자)

이 스니펫은 두 쿼리의 합집합(논리합(OR))을 만듭니다. 여기서 각 쿼리 결과는 최종 결과에 결합됩니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

Java

Datastore 모드용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Datastore 모드 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Datastore 모드 Java API 참고 문서를 확인하세요.

Datastore 모드에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.StructuredQuery.CompositeFilter;
import com.google.cloud.datastore.StructuredQuery.Filter;
import com.google.cloud.datastore.StructuredQuery.PropertyFilter;

public class OrFilterQuery {
  public static void invoke() throws Exception {

    // Instantiates a client
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
    String propertyName = "description";

    // Create the two filters
    Filter orFilter =
        CompositeFilter.or(
            PropertyFilter.eq(propertyName, "Feed cats"),
            PropertyFilter.eq(propertyName, "Buy milk"));

    // Build the query
    Query<Entity> query = Query.newEntityQueryBuilder().setKind("Task").setFilter(orFilter).build();

    // Get the results back from Datastore
    QueryResults<Entity> results = datastore.run(query);

    if (!results.hasNext()) {
      throw new Exception("query yielded no results");
    }

    while (results.hasNext()) {
      Entity entity = results.next();
      System.out.printf("Entity: %s%n", entity);
    }
  }
}

Python

Datastore 모드용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Datastore 모드 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Datastore 모드 Python API 참고 문서를 확인하세요.

Datastore 모드에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import datastore
from google.cloud.datastore import query


def query_filter_or(project_id: str) -> None:
    """Builds a union of two queries (OR) filter.

    Arguments:
        project_id: your Google Cloud Project ID
    """
    client = datastore.Client(project=project_id)

    or_query = client.query(kind="Task")
    or_filter = query.Or(
        [
            query.PropertyFilter("description", "=", "Buy milk"),
            query.PropertyFilter("description", "=", "Feed cats"),
        ]
    )

    or_query.add_filter(filter=or_filter)

    results = list(or_query.fetch())
    for result in results:
        print(result["description"])

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저 참조하기