更新及重建有效索引

如果搜尋查詢量很大,請務必更新索引,確保資訊準確無誤。您可以透過以下幾種方式更新向量搜尋索引:

取代整個索引

如要取代現有批次更新或串流 Index 的內容,請使用 IndexService.UpdateIndex 方法。

  • Index.metadata.contentsDeltaUri 設為包含要更新向量的 Cloud Storage URI。
  • Index.metadata.isCompleteOverwrite 設為 true。如果設為 true,系統會以您提供的新中繼資料檔案,完全覆寫整個索引。

gcloud

  1. 更新索引中繼資料檔案 ,設定 contentsDeltaUriisCompleteOverwrite=true
  2. 使用 gcloud ai indexes update 指令

使用下方的任何指令資料之前,請先替換以下項目:

  • LOCAL_PATH_TO_METADATA_FILE:中繼資料檔案的本機路徑。
  • INDEX_ID:索引的 ID。
  • LOCATION:您使用 Vertex AI 的區域。
  • PROJECT_ID:您的 Google Cloud 專案 ID

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud ai indexes update INDEX_ID \
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE \
    --region=LOCATION \
    --project=PROJECT_ID

Windows (PowerShell)

gcloud ai indexes update INDEX_ID `
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE `
    --region=LOCATION `
    --project=PROJECT_ID

Windows (cmd.exe)

gcloud ai indexes update INDEX_ID ^
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE ^
    --region=LOCATION ^
    --project=PROJECT_ID

REST

使用任何要求資料之前,請先替換以下項目:

  • INPUT_DIR:索引內容的 Cloud Storage 目錄路徑。
  • INDEX_ID:索引的 ID。
  • LOCATION:您使用 Vertex AI 的區域。
  • PROJECT_ID:您的 Google Cloud 專案 ID
  • PROJECT_NUMBER:系統自動為專案產生的專案編號

HTTP 方法和網址:

PATCH https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/indexes/INDEX_ID

JSON 要求主體:

{
 "metadata": {
   "contentsDeltaUri": "INPUT_DIR",
   "isCompleteOverwrite": true
 }
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/indexes/INDEX_ID/operations/OPERATION_ID",
 "metadata": {
   "@type": "type.googleapis.com/google.cloud.aiplatform.v1.UpdateIndexOperationMetadata",
   "genericMetadata": {
     "createTime": "2022-01-12T23:56:14.480948Z",
     "updateTime": "2022-01-12T23:56:14.480948Z"
   }
 }
}

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件

呼叫下列方法時,請將 is_complete_overwrite=True 設為完全取代索引內容。

def vector_search_update_index_embeddings(
    project: str,
    location: str,
    index_name: str,
    gcs_uri: str,
    is_complete_overwrite: Optional[bool] = None,
) -> None:
    """Update a vector search index.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_name (str): Required. The index to update. A fully-qualified index
          resource name or a index ID.  Example:
          "projects/123/locations/us-central1/indexes/my_index_id" or
          "my_index_id".
        gcs_uri (str): Required. The Google Cloud Storage uri for index content
        is_complete_overwrite (bool): Optional. If true, the index content will
          be overwritten wth the contents at gcs_uri.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index instance from an existing index
    index = aiplatform.MatchingEngineIndex(index_name=index_name)

    index.update_embeddings(
        contents_delta_uri=gcs_uri, is_complete_overwrite=is_complete_overwrite
    )

控制台

請按照這些操作說明更新批次索引內容。

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Deploy and Use」(部署及使用) 專區。選取「Vector Search」

    前往 Vector Search

  2. 選取要更新的索引。「索引資訊」頁面隨即開啟。
  3. 選取「編輯索引」。編輯索引窗格隨即開啟。
  4. 在「Cloud Storage」欄位中,搜尋並選取儲存向量資料的 Cloud Storage 資料夾。
  5. 勾選「完全覆寫」方塊,覆寫所有現有資料。
  6. 按一下 [Update] (更新)。
  7. 按一下「完成」關閉面板。

部分更新批次索引

如要更新現有批次的嵌入 Index,請使用 IndexService.UpdateIndex 方法。

  • Index.metadata.contentsDeltaUri 設為包含要更新向量的 Cloud Storage URI。
  • Index.metadata.isCompleteOverwrite 設為 false。

系統只會更新、插入或刪除 Index.metadata.contentsDeltaUri 中指定的向量。索引中的其他現有嵌入內容則會保留。

gcloud

  1. 更新索引中繼資料檔案 ,設定 。contentsDeltaUri
  2. 使用 gcloud ai indexes update 指令

使用下方的任何指令資料之前,請先替換以下項目:

  • LOCAL_PATH_TO_METADATA_FILE:中繼資料檔案的本機路徑。
  • INDEX_ID:索引的 ID。
  • LOCATION:您使用 Vertex AI 的區域。
  • PROJECT_ID:您的 Google Cloud 專案 ID

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud ai indexes update INDEX_ID \
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE \
    --region=LOCATION \
    --project=PROJECT_ID

Windows (PowerShell)

gcloud ai indexes update INDEX_ID `
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE `
    --region=LOCATION `
    --project=PROJECT_ID

Windows (cmd.exe)

gcloud ai indexes update INDEX_ID ^
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE ^
    --region=LOCATION ^
    --project=PROJECT_ID

REST

使用任何要求資料之前,請先替換以下項目:

  • INPUT_DIR:索引內容的 Cloud Storage 目錄路徑。
  • INDEX_ID:索引的 ID。
  • LOCATION:您使用 Vertex AI 的區域。
  • PROJECT_ID:您的 Google Cloud 專案 ID
  • PROJECT_NUMBER:系統自動為專案產生的專案編號

HTTP 方法和網址:

PATCH https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/indexes/INDEX_ID

JSON 要求主體:

{
 "metadata": {
   "contentsDeltaUri": "INPUT_DIR",
   "isCompleteOverwrite": false
 }
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/indexes/INDEX_ID/operations/OPERATION_ID",
 "metadata": {
   "@type": "type.googleapis.com/google.cloud.aiplatform.v1.UpdateIndexOperationMetadata",
   "genericMetadata": {
     "createTime": "2022-01-12T23:56:14.480948Z",
     "updateTime": "2022-01-12T23:56:14.480948Z"
   }
 }
}

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件

呼叫下列方法時,請設定 is_complete_overwrite=False

def vector_search_update_index_embeddings(
    project: str,
    location: str,
    index_name: str,
    gcs_uri: str,
    is_complete_overwrite: Optional[bool] = None,
) -> None:
    """Update a vector search index.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_name (str): Required. The index to update. A fully-qualified index
          resource name or a index ID.  Example:
          "projects/123/locations/us-central1/indexes/my_index_id" or
          "my_index_id".
        gcs_uri (str): Required. The Google Cloud Storage uri for index content
        is_complete_overwrite (bool): Optional. If true, the index content will
          be overwritten wth the contents at gcs_uri.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index instance from an existing index
    index = aiplatform.MatchingEngineIndex(index_name=index_name)

    index.update_embeddings(
        contents_delta_uri=gcs_uri, is_complete_overwrite=is_complete_overwrite
    )

控制台

請按照這些操作說明更新批次索引內容。

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Deploy and Use」(部署及使用) 專區。選取「Vector Search」

    前往 Vector Search

  2. 選取要更新的索引。「Index info」(索引資訊) 頁面隨即開啟。
  3. 選取「編輯索引」。編輯索引窗格隨即開啟。
  4. 在「Cloud Storage」欄位中,搜尋並選取儲存向量資料的 Cloud Storage 資料夾。
  5. 確認「完全覆寫」方塊未勾選。
  6. 按一下 [Update] (更新)。
  7. 按一下「完成」關閉面板。

如果 Index 有任何相關聯的部署作業 (請參閱「Index.deployed_indexes」欄位),當原始 Index 進行特定變更時,DeployedIndex 會在背景自動非同步更新,以反映這些變更。

如要檢查變更是否已傳播,請比較更新索引作業完成時間和 DeployedIndex.index_sync_time

部分更新串流索引

透過串流更新,您可以在幾秒內更新及查詢索引。 目前無法在現有的批次更新索引上使用串流更新,您必須建立新的索引。詳情請參閱「建立串流更新的索引」。

串流更新每使用 1 GB,就會產生 $0.45 美元的費用。如要進一步瞭解定價,請參閱 Vertex AI 定價頁面。 串流更新會直接套用至記憶體中已部署的索引,並在短暫延遲後反映在查詢結果中。

新增或更新資料點

請參閱這些範例,瞭解如何 upsert 資料點。請注意,upsert-datapoints 僅接受陣列格式的 JSON。

Python

Python

def vector_search_upsert_datapoints(
    project: str,
    location: str,
    index_name: str,
    datapoints: Sequence[aiplatform.compat.types.index_v1beta1.IndexDatapoint],
) -> None:
    """Upsert datapoints to the index.

    Args:
      project (str): Required. The Project ID
      location (str): Required. The region name, e.g. "us-central1"
      index_name (str): Required. The index to update. A fully-qualified index
        resource name or a index ID.  Example:
        "projects/123/locations/us-central1/indexes/my_index_id" or
        "my_index_id".
      datapoints: Sequence[IndexDatapoint]: Required. The datapoints to be
        updated. For example:
        [IndexDatapoint(datapoint_id="1", feature_vector=[1.0, 2.0, 3.0]),
        IndexDatapoint(datapoint_id="2", feature_vector=[4.0, 5.0, 6.0])]
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index instance from an existing index with stream_update
    # enabled
    my_index = aiplatform.MatchingEngineIndex(index_name=index_name)

    # Upsert the datapoints to the index
    my_index.upsert_datapoints(datapoints=datapoints)

Curl

處理量配額限制與 upsert 中包含的資料量有關。 如果索引中已有資料點 ID,系統會更新嵌入內容,否則會新增嵌入內容。

  
  DATAPOINT_ID_1=
  DATAPOINT_ID_2=
  curl -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/indexes/${INDEX_ID}:upsertDatapoints \
  -d '{datapoints: [{datapoint_id: "'${DATAPOINT_ID_1}'", feature_vector: [...]},
  {datapoint_id: "'${DATAPOINT_ID_2}'", feature_vector: [...]}]}'
  
  

混合式搜尋支援資料點的稀疏和密集嵌入表示法。在 upsert 作業中,如果省略密集嵌入,系統會刪除密集表示法;如果省略稀疏嵌入,系統會刪除稀疏表示法。

這個範例會更新稠密型和稀疏型嵌入。

  
    curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`"  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/indexes/${INDEX_ID}:upsertDatapoints -d '{datapoints: [{datapoint_id: "111", feature_vector: [0.111, 0.111], "sparse_embedding": {"values": [111.0,111.1,111.2], "dimensions": [10,20,30]}}]}'
  
  

這個範例會更新密集嵌入,並移除稀疏嵌入。

    
      curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`"  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/indexes/${INDEX_ID}:upsertDatapoints -d '{datapoints: [{datapoint_id: "111", feature_vector: [0.111, 0.111]}]}'
    
  

這個範例會更新稀疏嵌入,並移除密集嵌入。

    
      curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`"  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/indexes/${INDEX_ID}:upsertDatapoints -d '{datapoints: [{datapoint_id: "111",  "sparse_embedding": {"values": [111.0,111.1,111.2], "dimensions": [10,20,30]}}]}'
    
  

控制台

控制台

請按照這些操作說明,將內容更新至串流索引。

  1. 前往 Google Cloud 控制台的「Vector Search」頁面。

    前往 Vector Search

  2. 選取要更新的索引。「Index info」(索引資訊) 頁面隨即開啟。
  3. 按一下「編輯索引」。編輯索引窗格隨即開啟。
  4. 在窗格中選取「Upsert data point」(插入/更新資料點) 分頁標籤,即可新增內容。
  5. 輸入資料點 ID。
  6. 輸入至少一種嵌入內容:
    • 密集型嵌入:輸入以半形逗號分隔的浮點值陣列。值的數量必須與索引的維度相符。
    • 稀疏嵌入
      1. 請輸入稀疏型嵌入維度,並以半形逗號分隔整數。值的數量不必與索引的維度相符。
      2. 輸入值時,請使用以半形逗號分隔的浮點值陣列。值的數量必須與稀疏型嵌入維度的數量相符。
  7. 選用:如要啟用依權杖限制篩選這個資料點,請按一下「新增權杖限制」,然後輸入命名空間和以半形逗號分隔的字串做為權杖。
  8. 選用:如要啟用依數值限制篩選這個資料點,請按一下「新增數值限制」,輸入命名空間,選取數字類型,然後輸入值。
  9. 選用:輸入擁擠標記字串,避免出現許多類似結果。
  10. 按一下「Upsert」Upsert
  11. 按一下「完成」關閉面板。

處理量配額限制與 upsert 中包含的資料量有關。 如果資料點 ID 存在於索引中,系統會更新嵌入內容,否則會新增嵌入內容。

更新嵌入中繼資料

您可能需要更新串流限制或數字限制的原因有很多,舉例來說,處理大量快速變動的資料時,您可能想優先處理特定資料串流。直接更新限制或數值限制,可讓您即時調整焦點,確保系統立即處理或醒目顯示最重要的資料。

您可以在串流索引中直接更新資料點限制和數值限制,不必支付完整更新的壓縮成本。

如要執行這類僅限中繼資料的更新,請在要求中加入 update_mask 欄位。update_mask 的值必須設為 all_restricts。 資料點中設定的限制和數值限制值,應為您要在更新中套用的新值。

以下範例說明如何將限制新增至兩個現有資料點。

DATAPOINT_ID_1=
DATAPOINT_ID_2=

curl -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/indexes/${INDEX_ID}:upsertDatapoints \
-d '{datapoints:
[{datapoint_id: "'${DATAPOINT_ID_1}'", feature_vector: [...],  restricts:[{namespace: "color", allow_list: ["red"]}]},
{datapoint_id: "'${DATAPOINT_ID_2}'", feature_vector: [...],  restricts:[{namespace: "color", allow_list: ["red"]}]}
], update_mask: "all_restricts"}'

移除資料點

您可能需要從串流索引中移除資料點。您可以使用 curl 或 Google Cloud 控制台執行這項操作。

從索引中刪除資料點的主要用途,是為了維持索引與實際來源之間的同位性。以書商為例,他們會使用向量嵌入來表示書籍庫存,以利搜尋和推薦。如果書籍售完或從庫存中移除,請從索引中刪除對應的資料點,確保搜尋結果和推薦內容準確無誤且為最新狀態。

Curl


curl -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/indexes/{INDEX_ID}:removeDatapoints -d '{datapoint_ids: ["'{DATAPOINT_ID_1}'", "'{DATAPOINT_ID_2}'"]}'

控制台

控制台

按照這些指示從串流索引刪除資料點。

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Deploy and Use」(部署及使用) 專區。選取「Vector Search」

    前往 Vector Search

  2. 選取要更新的串流索引。「Index info」(索引資訊) 頁面隨即開啟。
  3. 選取「編輯索引」。編輯索引窗格隨即開啟。
  4. 在窗格中,選取「移除資料點」分頁標籤。
  5. 提供以半形逗號分隔的資料點 ID 清單,最多可新增 20 個資料點
  6. 按一下 [移除]
  7. 按一下「完成」關閉面板。

Python

Python

def vector_search_remove_datapoints(
    project: str,
    location: str,
    index_name: str,
    datapoint_ids: Sequence[str],
) -> None:
    """Remove datapoints from a vector search index.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_name (str): Required. The index to update. A fully-qualified index
          resource name or a index ID.  Example:
          "projects/123/locations/us-central1/indexes/my_index_id" or
          "my_index_id".
        datapoint_ids (Sequence[str]): Required. The datapoint IDs to remove.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index instance from an existing index
    index = aiplatform.MatchingEngineIndex(index_name=index_name)

    index.remove_datapoints(datapoint_ids=datapoint_ids)

更新索引中繼資料

IndexService.UpdateIndex 也可用於更新批次和串流索引的中繼資料欄位 display_namedescriptionlabels。請注意,單次呼叫 UpdateIndex 即可更新索引嵌入 這些中繼資料欄位,但無法同時更新兩者。

gcloud

  1. 更新索引中繼資料檔案
  2. 使用 gcloud ai indexes update 指令

使用下方的任何指令資料之前,請先替換以下項目:

  • LOCAL_PATH_TO_METADATA_FILE:中繼資料檔案的本機路徑。
  • INDEX_ID:索引的 ID。
  • LOCATION:您使用 Vertex AI 的區域。
  • PROJECT_ID:您的 Google Cloud 專案 ID

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud ai indexes update INDEX_ID \
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE \
    --region=LOCATION \
    --project=PROJECT_ID

Windows (PowerShell)

gcloud ai indexes update INDEX_ID `
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE `
    --region=LOCATION `
    --project=PROJECT_ID

Windows (cmd.exe)

gcloud ai indexes update INDEX_ID ^
    --metadata-file=LOCAL_PATH_TO_METADATA_FILE ^
    --region=LOCATION ^
    --project=PROJECT_ID

REST

使用任何要求資料之前,請先替換以下項目:

  • INPUT_DIR:索引內容的 Cloud Storage 目錄路徑。
  • INDEX_ID:索引的 ID。
  • LOCATION:您使用 Vertex AI 的區域。
  • PROJECT_ID:您的 Google Cloud 專案 ID
  • PROJECT_NUMBER:系統自動為專案產生的專案編號

HTTP 方法和網址:

PATCH https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/indexes/INDEX_ID

JSON 要求主體:

{
 "metadata": {
   "description": "Updated description",
   "display_name": "Updated display name"
 }
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/indexes/INDEX_ID/operations/OPERATION_ID",
 "metadata": {
   "@type": "type.googleapis.com/google.cloud.aiplatform.v1.UpdateIndexOperationMetadata",
   "genericMetadata": {
     "createTime": "2022-01-12T23:56:14.480948Z",
     "updateTime": "2022-01-12T23:56:14.480948Z"
   }
 }
}

Python

def vector_search_update_index_metadata(
    project: str,
    location: str,
    index_name: str,
    display_name: Optional[str] = None,
    description: Optional[str] = None,
    labels: Optional[Dict[str, str]] = None,
) -> None:
    """Update a vector search index.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_name (str): Required. The index to update. A fully-qualified index
          resource name or a index ID.  Example:
          "projects/123/locations/us-central1/indexes/my_index_id" or
          "my_index_id".
        display_name (str): Optional. The display name of the Index. The name
          can be up to 128 characters long and can be consist of any UTF-8
          characters.
        description (str): Optional. The description of the Index.
        labels (Dict[str, str]): Optional. The labels with user-defined
          metadata to organize your Indexs. Label keys and values can be no
          longer than 64 characters (Unicode codepoints), can only contain
          lowercase letters, numeric characters, underscores and dashes.
          International characters are allowed. See https://goo.gl/xmQnxf for
          more information on and examples of labels. No more than 64 user
          labels can be associated with one Index (System labels are excluded).
          System reserved label keys are prefixed with
          "aiplatform.googleapis.com/" and are immutable.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index instance from an existing index
    index = aiplatform.MatchingEngineIndex(index_name=index_name)

    index.update_metadata(
        display_name=display_name,
        description=description,
        labels=labels,
    )

控制台

請按照這些操作說明更新索引中繼資料 (控制台只能更新 display_namedescription)。

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Deploy and Use」(部署及使用) 專區。選取「Vector Search」

    前往 Vector Search

  2. 選取要更新的索引。「Index info」(索引資訊) 頁面隨即開啟。
  3. 選取「編輯索引」。編輯索引窗格隨即開啟。
  4. 更新所需的中繼資料欄位。
  5. 按一下 [Update] (更新)。
  6. 按一下「完成」關閉面板。

壓實

系統會定期重建索引,以納入上次重建後的所有新更新。這項重建或「壓縮」作業可提升查詢效能和可靠性。壓縮作業適用於串流更新和批次更新。

  • 串流更新:Vector Search 會使用啟發式指標判斷何時觸發壓縮作業。如果最舊的未壓縮資料已留存五天,系統一律會觸發壓縮作業。除了串流更新費用外,系統也會以批次更新的費率,向您收取重建索引的費用。

  • 批次更新:當增量資料集大小超過基礎資料集大小的 20% 時,就會發生批次更新。

重建及查詢索引

您可以使用 grpc cli、用戶端程式庫或 Python 適用的 Vertex AI SDK,照常傳送比對或批次比對要求。重建查詢後,您應該會在幾秒內看到更新。如要瞭解如何查詢索引,請參閱「查詢索引以取得最鄰近的項目」。

選填欄位

建立索引時,您可以運用一些選用欄位微調查詢。

使用限制條件進行 upsert 作業

插入或更新索引並新增限制,即可為資料點加上標記,讓資料點在查詢時已識別完成,可供篩選。您可以在傳送查詢前新增限制標記,限制資料顯示的結果。舉例來說,假設顧客想對索引執行查詢,但希望搜尋鞋類時,結果只顯示符合「紅色」的項目。在以下範例中,索引正在進行 upsert 作業,並篩選所有紅色鞋子,但拒絕藍色鞋子。這可確保搜尋篩選器在執行前,會從大型且多樣的索引中,篩選出最合適的特定選項。

除了權杖限制,這個範例也使用了數值限制。在本例中,資料點與價格 20、長度 0.3 和寬度 0.5 相關聯。查詢時,您可以使用這些數字限制來篩選結果,限制查詢結果的價格、長度和寬度值。舉例來說,如果查詢篩選條件為價格 > 25、長度 < 1 且寬度 < 1,就會顯示這個資料點。

如要進一步瞭解篩選功能,請參閱「Vector Search for Indexing」。

Python

# Upsert datapoints
_TEST_DATAPOINT_1 = aiplatform_v1.types.index.IndexDatapoint(
    datapoint_id="3",
    feature_vector=[0.00526886899, -0.0198396724],
    restricts=[
        aiplatform_v1.types.index.IndexDatapoint.Restriction(namespace="Color", allow_list=["red"])
    ],
    numeric_restricts=[
        aiplatform_v1.types.index.IndexDatapoint.NumericRestriction(
            namespace="cost",
            value_int=1,
        )
    ],
)
_TEST_DATAPOINT_2 =  aiplatform_v1.types.index.IndexDatapoint(
    datapoint_id="4",
    feature_vector=[0.00526886899, -0.0198396724],
    numeric_restricts=[
        aiplatform_v1.types.index.IndexDatapoint.NumericRestriction(
            namespace="cost",
            value_double=0.1,
        )
    ],
    crowding_tag=aiplatform_v1.types.index.IndexDatapoint.CrowdingTag(crowding_attribute="crowding"),
)
_TEST_DATAPOINT_3 = aiplatform_v1.types.index.IndexDatapoint(
    datapoint_id="5",
    feature_vector=[0.00526886899, -0.0198396724],
    numeric_restricts=[
        aiplatform_v1.types.index.IndexDatapoint.NumericRestriction(
            namespace="cost",
            value_float=1.1,
        )
    ],
)

_TEST_DATAPOINTS = [_TEST_DATAPOINT_1, _TEST_DATAPOINT_2, _TEST_DATAPOINT_3]

my_streaming_index = my_streaming_index.upsert_datapoints(datapoints=_TEST_DATAPOINTS)

# Dynamic metadata update
_TEST_DATAPOINT_4 = aiplatform_v1.types.index.IndexDatapoint(
    datapoint_id="-2",
    numeric_restricts=[
        aiplatform_v1.types.index.IndexDatapoint.NumericRestriction(
            namespace="cost",
            value_float=1.1,
        )
    ],
)
my_streaming_index = my_streaming_index.upsert_datapoints(datapoints=[_TEST_DATAPOINT4], update_mask=["all_restricts"])

curl

curl -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://${ENDPOINT}/v1/projects/${PROJECT_ID}/locations/us-central1/indexes/${INDEX_ID}:upsertDatapoints \
-d '{
datapoints: [
  {
    datapoint_id: "'${DATAPOINT_ID_1}'",
    feature_vector: [...],
    restricts: { namespace: "color", allow_list: ["red"], deny_list: ["blue"]},
    numeric_restricts: [{namespace: "price", value_int: 20}, {namespace: "length", value_float: 0.3}, {namespace: "width", value_double: 0.5}]
  }
]}'

使用擁擠度進行 upsert

擁擠標記會提升結果多樣性,藉此限制類似結果。 擁擠是最近鄰項搜尋產生的鄰項清單限制,要求一組結果中,crowding_attribute 的值相同者不得超過某個值。舉例來說,假設您恢復連線後,繼續在網路上購買鞋子。您希望在結果中看到各種顏色,但可能希望這些顏色都屬於同一種款式,例如足球釘鞋。假設您在插入資料點時將 crowding_attribute 設為鞋子的顏色,則可以在查詢中將 per_crowding_attribute_num_neighbors 設為 3,要求系統傳回最多 3 雙相同顏色的鞋子。

這個欄位代表允許的相同擁擠標記比對次數上限。

curl -H "Content-Type: application/json" -H "Authorization: Bearer `gcloud auth print-access-token`" https://${ENDPOINT}/v1/projects/${PROJECT_ID}/locations/us-central1/indexes/${INDEX_ID}:upsertDatapoints \
-d '{
datapoints: [
  {
    datapoint_id: "'${DATAPOINT_ID_1}'",
    feature_vector: [...],
    restricts: { namespace: "type", allow_list: ["cleats"]}
    crowding_tag: { crowding_attribute: "red-shoe"},
  }
]}'

後續步驟