שאילתה באינדקס ציבורי כדי לקבל את השכנים הקרובים ביותר

אחרי שיוצרים את האינדקס ומפעילים אותו, אפשר להריץ שאילתות כדי לקבל את השכנים הקרובים ביותר.

הנה כמה דוגמאות לשאילתת התאמה למציאת השכנים הקרובים ביותר באמצעות אלגוריתם השכנים הקרובים (k-NN).

שאילתות לדוגמה לנקודת קצה ציבורית

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python 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 שמופיע בהמשך בDeploy, והוא מעוצב כ-<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 אפשר לראות איך מתקשרים מלקוחות http(s), למרות שהנקודה הציבורית תומכת בפרוטוקול כפול ל-RESTful ול-grpc_cli.


  $ 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"]}]}}]}'
  

המסוף

אתם יכולים להיעזר בהוראות האלה כדי להריץ שאילתה על אינדקס שנפרס בנקודת קצה ציבורית מהמסוף.

  1. בקטע Agent Platform במסוף Cloud de Confiance , עוברים לקטע Deploy and Use. בוחרים באפשרות חיפוש וקטורי.

    לדף חיפוש וקטורי

  2. בוחרים את האינדקס שרוצים לשלוח אליו שאילתה. ייפתח הדף פרטי האינדקס.
  3. גוללים למטה לקטע Deployed indexes (מדדים שנפרסו) ובוחרים את המדד שנפרס שרוצים לשלוח לו שאילתה. ייפתח הדף Deployed index info (פרטי אינדקס שנפרס).
  4. בקטע Query index, בוחרים אם לבצע שאילתה לפי ערך הטמעה צפוף, ערך הטמעה דליל, ערך הטמעה היברידי (הטמעות צפופות ודלילות) או נקודת נתונים ספציפית.
  5. מזינים את פרמטרים של שאילתה לסוג השאילתה שבחרתם. לדוגמה, אם אתם מבצעים שאילתה לפי הטמעה צפופה, מזינים את וקטור ההטמעה כדי לבצע את השאילתה.
  6. מריצים את השאילתה באמצעות פקודת curl שסופקה, או באמצעות Cloud Shell.
  7. אם משתמשים ב-Cloud Shell, בוחרים באפשרות Run in Cloud Shell (הפעלה ב-Cloud Shell).
  8. מריצים ב-Cloud Shell.
  9. התוצאות שמתקבלות הן השכנים הקרובים ביותר.

שאילתות היברידיות

חיפוש היברידי משתמש בהטמעות צפופות ודלילות לחיפושים שמבוססים על שילוב של חיפוש מילות מפתח וחיפוש סמנטי.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python 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 ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python 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,
    )

שורת פקודה

אפשר למצוא את PUBLIC_ENDPOINT_DOMAIN שמופיע בהמשך באינדקס הפריסה בפורמט <number>.<region>-<number>.vdb.vertexai.goog.

בדוגמה הזו של 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"]}]}}]}'
  

הגדרות שמשפיעות על הביצועים בזמן השאילתה

הפרמטרים הבאים של זמן השאילתה יכולים להשפיע על זמן האחזור, הזמינות והעלות כשמשתמשים בחיפוש וקטורי. ההנחיות האלה רלוונטיות לרוב המקרים. עם זאת, מומלץ תמיד לערוך ניסויים בהגדרות כדי לוודא שהן מתאימות לתרחיש השימוש שלכם.

הגדרות הפרמטרים מפורטות במאמר בנושא פרמטרים של הגדרת אינדקס.

פרמטר מידע כללי השפעה על הביצועים
approximateNeighborsCount

ההגדרה הזו מציינת לאלגוריתם את מספר התוצאות המשוערות שיש לאחזר מכל רסיס.

הערך של approximateNeighborsCount צריך להיות תמיד גדול מהערך של setNeighborsCount. אם הערך של setNeighborsCount קטן, מומלץ להגדיר את הערך של approximateNeighborsCount כ-10 פעמים הערך הזה. אם הערכים של setNeighborsCount גדולים יותר, אפשר להשתמש במכפיל קטן יותר.

השם התואם של ה-API בארכיטקטורת REST בשדה הזה הוא approximate_neighbor_count.

הגדלת הערך של approximateNeighborsCount יכולה להשפיע על הביצועים בדרכים הבאות:

  • זכירה: עלייה
  • זמן האחזור: יכול להיות שיהיה ארוך יותר
  • זמינות: אין השפעה
  • עלות: יכולה לעלות כי יותר נתונים מעובדים במהלך החיפוש

הקטנת הערך של approximateNeighborsCount יכולה להשפיע על הביצועים בדרכים הבאות:

  • Recall: Decreased
  • זמן האחזור: יכול להיות שירד
  • זמינות: אין השפעה
  • עלות: יכולה להפחית את העלות כי פחות נתונים מעובדים במהלך חיפוש
setNeighborCount

מציין את מספר התוצאות שרוצים שהשאילתה תחזיר.

השם התואם של ה-API בארכיטקטורת REST בשדה הזה הוא neighbor_count.

ערכים שקטנים מ-300 או שווים ל-300 לא פוגעים בביצועים ברוב תרחישי השימוש. אם הערכים גדולים יותר, כדאי לבדוק את התרחיש הספציפי שלכם.

fractionLeafNodesToSearch קובע את אחוז הצמתים העלים שיש לבקר בהם כשמחפשים שכנים קרובים. זה קשור לleafNodeEmbeddingCount כי ככל שיש יותר הטמעות לכל צומת עלה, כך נבדקים יותר נתונים לכל עלה.

השם התואם של ה-API בארכיטקטורת REST בשדה הזה הוא fraction_leaf_nodes_to_search_override.

הגדלת הערך של fractionLeafNodesToSearch יכולה להשפיע על הביצועים בדרכים הבאות:

  • זכירה: עלייה
  • זמן טעינה: מוגבר
  • זמינות: אין השפעה
  • עלות: יכולה לעלות כי זמן האחזור הגבוה תופס יותר משאבי מכונה

הקטנת הערך של fractionLeafNodesToSearch יכולה להשפיע על הביצועים בדרכים הבאות:

  • Recall: Decreased
  • זמן טעינה: ירידה
  • זמינות: אין השפעה
  • עלות: יכולה לרדת כי זמן האחזור הנמוך יותר תופס פחות משאבי מכונה