공개 색인을 쿼리하여 최근접 이웃 가져오기

색인을 만들고 배포한 후 쿼리를 실행하여 최근접 이웃을 가져올 수 있습니다.

다음은 k최근접 이웃 알고리즘(k-NN)을 사용하여 최근접 이웃을 찾는 일치 쿼리 예시입니다.

공개 엔드포인트의 쿼리 예시

Python용 Vertex AI SDK

Vertex AI SDK for Python을 설치하거나 업데이트하는 방법은 Vertex AI SDK for Python 설치를 참조하세요. 자세한 내용은 Python용 Vertex AI SDK API 참조 문서를 확인하세요.

def vector_search_find_neighbors(
    project: str,
    location: str,
    index_endpoint_name: str,
    deployed_index_id: str,
    queries: List[List[float]],
    num_neighbors: int,
) -> List[
    List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]
]:
    """Query the vector search index.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_endpoint_name (str): Required. Index endpoint to run the query
        against.
        deployed_index_id (str): Required. The ID of the DeployedIndex to run
        the queries against.
        queries (List[List[float]]): Required. A list of queries. Each query is
        a list of floats, representing a single embedding.
        num_neighbors (int): Required. The number of neighbors to return.

    Returns:
        List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index endpoint instance from an existing endpoint.
    my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint(
        index_endpoint_name=index_endpoint_name
    )

    # Query the index endpoint for the nearest neighbors.
    return my_index_endpoint.find_neighbors(
        deployed_index_id=deployed_index_id,
        queries=queries,
        num_neighbors=num_neighbors,
    )

명령줄

아래에 나열된 publicEndpointDomainName배포에서 찾을 수 있으며 형식은 <number>.<region>-<number>.vdb.vertexai.goog입니다.


  $ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://1957880287.us-central1-181224308459.vdb.vertexai.goog/v1/projects/181224308459/locations/us-central1/indexEndpoints/3370566089086861312:findNeighbors -d '{deployed_index_id: "test_index_public1", queries: [{datapoint: {datapoint_id: "0", feature_vector: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, neighbor_count: 5}]}'
  

이 curl 예시는 공개 엔드포인트가 restful 및 grpc_cli에 대한 이중 프로토콜을 지원하더라도 http(s) 클라이언트에서 호출을 수행하는 방법을 보여줍니다.


  $ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://1957880287.us-central1-181224308459.vdb.vertexai.goog/v1/projects/${PROJECT_ID}/locations/us-central1/indexEndpoints/${INDEX_ENDPOINT_ID}:readIndexDatapoints -d '{deployed_index_id:"test_index_public1", ids: ["606431", "896688"]}'
  

이 curl 예시에서는 토큰 및 숫자 제한을 사용하여 쿼리하는 방법을 보여줍니다.


  $ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`"  https://${PUBLIC_ENDPOINT_DOMAIN}/v1/projects/${PROJECT_ID}/locations/${LOCATION}/indexEndpoints/${INDEX_ENDPOINT_ID}:findNeighbors -d '{deployed_index_id:"${DEPLOYED_INDEX_ID}", queries: [{datapoint: {datapoint_id:"x", feature_vector: [1, 1], "sparse_embedding": {"values": [111.0,111.1,111.2], "dimensions": [10,20,30]}, numeric_restricts: [{namespace: "int-ns", value_int: -2, op: "GREATER"}, {namespace: "int-ns", value_int: 4, op: "LESS_EQUAL"}, {namespace: "int-ns", value_int: 0, op: "NOT_EQUAL"}], restricts: [{namespace: "color", allow_list: ["red"]}]}}]}'
  

Console

다음 안내에 따라 콘솔에서 공개 엔드포인트에 배포된 색인을 쿼리합니다.

  1. 콘솔의 Vertex AI 섹션에서 Google Cloud 배포 및 사용 섹션으로 이동합니다. 벡터 검색을 선택합니다.

    벡터 검색으로 이동

  2. 쿼리할 색인을 선택합니다. 색인 정보 페이지가 열립니다.
  3. 배포된 색인 섹션으로 아래로 스크롤하여 쿼리할 배포된 색인을 선택합니다. 배포된 색인 정보 페이지가 열립니다.
  4. 쿼리 색인 섹션에서 쿼리 방법을 밀집 임베딩 값, 희소 임베딩 값, 하이브리드 임베딩 값(밀집 및 희소 임베딩) 또는 특정 데이터 포인트 중에서 선택합니다.
  5. 선택한 쿼리 유형의 쿼리 매개변수를 입력합니다. 예를 들어 밀집 임베딩으로 쿼리하는 경우 쿼리할 임베딩 벡터를 입력합니다.
  6. 제공된 curl 명령어를 사용하거나 Cloud Shell을 사용하여 쿼리를 실행합니다.
  7. Cloud Shell을 사용하는 경우 Cloud Shell에서 실행을 선택합니다.
  8. Cloud Shell에서 실행
  9. 결과로 최근접 이웃이 반환됩니다.

하이브리드 쿼리

하이브리드 검색은 키워드 검색과 시맨틱 검색을 조합하여 검색할 때 밀집 임베딩과 희소 임베딩을 모두 사용합니다.

Python용 Vertex AI SDK

Vertex AI SDK for Python을 설치하거나 업데이트하는 방법은 Vertex AI SDK for Python 설치를 참조하세요. 자세한 내용은 Python용 Vertex AI SDK API 참조 문서를 확인하세요.

def vector_search_find_neighbors_hybrid_queries(
    project: str,
    location: str,
    index_endpoint_name: str,
    deployed_index_id: str,
    num_neighbors: int,
) -> List[
    List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]
]:
    """Query the vector search index using example hybrid queries.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_endpoint_name (str): Required. Index endpoint to run the query
        against.
        deployed_index_id (str): Required. The ID of the DeployedIndex to run
        the queries against.
        num_neighbors (int): Required. The number of neighbors to return.

    Returns:
        List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index endpoint instance from an existing endpoint.
    my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint(
        index_endpoint_name=index_endpoint_name
    )

    # Query hybrid datapoints, sparse-only datapoints, and dense-only datapoints.
    hybrid_queries = [
        aiplatform.matching_engine.matching_engine_index_endpoint.HybridQuery(
            dense_embedding=[1, 2, 3],
            sparse_embedding_dimensions=[10, 20, 30],
            sparse_embedding_values=[1.0, 1.0, 1.0],
            rrf_ranking_alpha=0.5,
        ),
        aiplatform.matching_engine.matching_engine_index_endpoint.HybridQuery(
            dense_embedding=[1, 2, 3],
            sparse_embedding_dimensions=[10, 20, 30],
            sparse_embedding_values=[0.1, 0.2, 0.3],
        ),
        aiplatform.matching_engine.matching_engine_index_endpoint.HybridQuery(
            sparse_embedding_dimensions=[10, 20, 30],
            sparse_embedding_values=[0.1, 0.2, 0.3],
        ),
        aiplatform.matching_engine.matching_engine_index_endpoint.HybridQuery(
            dense_embedding=[1, 2, 3]
        ),
    ]

    return my_index_endpoint.find_neighbors(
        deployed_index_id=deployed_index_id,
        queries=hybrid_queries,
        num_neighbors=num_neighbors,
    )

필터링 및 크라우딩이 있는 쿼리

벡터 일치 필터링을 사용하면 최근접 이웃 결과를 특정 카테고리로 제한할 수 있습니다. 필터를 사용하면 검색 결과에서 제외할 카테고리를 지정할 수도 있습니다.

크라우딩 이웃별 제한은 색인 데이터의 단일 크라우딩 태그에서 반환되는 결과 수를 제한하여 결과 다양성을 높일 수 있습니다.

Python용 Vertex AI SDK

Vertex AI SDK for Python을 설치하거나 업데이트하는 방법은 Vertex AI SDK for Python 설치를 참조하세요. 자세한 내용은 Python용 Vertex AI SDK API 참조 문서를 확인하세요.

def vector_search_find_neighbors_filtering_crowding(
    project: str,
    location: str,
    index_endpoint_name: str,
    deployed_index_id: str,
    queries: List[List[float]],
    num_neighbors: int,
    filter: List[aiplatform.matching_engine.matching_engine_index_endpoint.Namespace],
    numeric_filter: List[
        aiplatform.matching_engine.matching_engine_index_endpoint.NumericNamespace
    ],
    per_crowding_attribute_neighbor_count: int,
) -> List[
    List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]
]:
    """Query the vector search index with filtering and crowding.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_endpoint_name (str): Required. Index endpoint to run the query
        against.
        deployed_index_id (str): Required. The ID of the DeployedIndex to run
        the queries against.
        queries (List[List[float]]): Required. A list of queries. Each query is
        a list of floats, representing a single embedding.
        num_neighbors (int): Required. The number of neighbors to return.
        filter (List[Namespace]): Required. A list of Namespaces for filtering
        the matching results. For example,
        [Namespace("color", ["red"], []), Namespace("shape", [], ["square"])]
        will match datapoints that satisfy "red color" but not include
        datapoints with "square shape".
        numeric_filter (List[NumericNamespace]): Required. A list of
        NumericNamespaces for filtering the matching results. For example,
        [NumericNamespace(name="cost", value_int=5, op="GREATER")] will limit
        the matching results to datapoints with cost greater than 5.
        per_crowding_attribute_neighbor_count (int): Required. The maximum
        number of returned matches with the same crowding tag.

    Returns:
        List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index endpoint instance from an existing endpoint.
    my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint(
        index_endpoint_name=index_endpoint_name
    )

    # Query the index endpoint for the nearest neighbors.
    return my_index_endpoint.find_neighbors(
        deployed_index_id=deployed_index_id,
        queries=queries,
        num_neighbors=num_neighbors,
        filter=filter,
        numeric_filter=numeric_filter,
        per_crowding_attribute_neighbor_count=per_crowding_attribute_neighbor_count,
    )

성능에 영향을 미치는 쿼리 시간 설정

다음 쿼리 시간 매개변수는 벡터 검색을 사용할 때 지연 시간, 가용성, 비용에 영향을 미칠 수 있습니다. 이 가이드는 대부분의 케이스에 적용됩니다. 하지만 항상 구성으로 실험하여 사용 사례에 적합한지 확인해야 합니다.

매개변수 정의는 색인 구성 매개변수를 참조하세요.

매개변수 소개 성능 영향
approximateNeighborsCount

각 샤드에서 검색할 적합한 결과 수를 알고리즘에 알려줍니다.

approximateNeighborsCount 값은 항상 setNeighborsCount 값보다 커야 합니다. setNeighborsCount 값이 작으면 approximateNeighborsCount에 이 값의 10배가 권장됩니다. setNeighborsCount 값이 크면 더 작은 배수를 사용할 수 있습니다.

이 필드의 상응하는 REST API 이름은 approximate_neighbor_count입니다.

approximateNeighborsCount 값을 늘리면 다음과 같이 성능이 영향을 받을 수 있습니다.

  • 재현율: 증가
  • 지연 시간: 잠재적으로 증가
  • 가용성: 영향 없음
  • 비용: 검색 중에 더 많은 데이터가 처리되므로 증가할 수 있음

approximateNeighborsCount 값을 줄이면 다음과 같이 성능이 영향을 받을 수 있습니다.

  • 재현율: 감소
  • 지연 시간: 잠재적으로 감소
  • 가용성: 영향 없음
  • 비용: 검색 중에 더 적은 데이터가 처리되므로 비용이 감소할 수 있음
setNeighborCount

쿼리에서 반환할 결과 수를 지정합니다.

이 필드의 상응하는 REST API 이름은 neighbor_count입니다.

값이 300이하면 대부분의 사용 사례에서 성능이 유지됩니다. 값이 더 크면 특정 사용 사례에 맞게 테스트합니다.

fractionLeafNodesToSearch 최근접 이웃을 검색할 때 방문할 리프 노드 비율을 제어합니다. 이는 리프 노드당 임베딩이 많을수록 리프당 더 많은 데이터가 검사된다는 점에서 leafNodeEmbeddingCount와 관련이 있습니다.

이 필드의 상응하는 REST API 이름은 fraction_leaf_nodes_to_search_override입니다.

fractionLeafNodesToSearch 값을 늘리면 다음과 같이 성능이 영향을 받을 수 있습니다.

  • 재현율: 증가
  • 지연 시간: 증가
  • 가용성: 영향 없음
  • 비용: 지연 시간이 높을수록 머신 리소스를 더 많이 점유하므로 증가할 수 있음

fractionLeafNodesToSearch 값을 줄이면 다음과 같이 성능이 영향을 받을 수 있습니다.

  • 재현율: 감소
  • 지연 시간: 감소
  • 가용성: 영향 없음
  • 비용: 지연 시간이 낮을수록 머신 리소스를 더 적게 점유하므로 감소할 수 있음

다음 단계

색인을 만드는 방법, 공개 엔드포인트에 배포하는 방법, 쿼리 방법에 대한 엔드 투 엔드 예시를 보려면 공식 노트북의 StackOverflow 질문에 벡터 검색 및 텍스트용 Vertex AI 임베딩 사용을 참조하세요.