獨特屬性

    獨特屬性是一個特殊的、使用者指定的欄位。它最常被用來防止 Meilisearch 回傳一組多個相似的文件,而是強制它只回傳一個。

    您可以使用兩種方式設定獨特屬性:在設定期間使用 distinctAttribute 索引設定,或是在搜尋時使用 distinct 搜尋參數。

    在設定期間設定獨特屬性

    distinctAttribute 是一個索引設定,它設定 Meilisearch 應用於該索引中所有搜尋和 facet 擷取的預設獨特屬性。

    警告

    每個索引只能有一個 distinctAttribute。嘗試設定多個欄位作為 distinctAttribute 將會傳回錯誤。

    設定為獨特屬性的欄位值在傳回的文件中將永遠是唯一的。這表示**在傳回的文件中,獨特屬性欄位中永遠不會出現同一個值超過一次**。

    當多個文件對於獨特屬性具有相同的值時,Meilisearch 只會在套用排序規則後傳回排名最高的結果。如果兩個或多個文件在排名方面是等效的,Meilisearch 會根據其 internal_id 傳回第一個結果。

    範例

    假設您有一個電子商務資料集。對於包含有關夾克資訊的索引,您可能會有多個相同項目,但只有顏色或尺寸等微小的差異。

    如下所示,此資料集包含三個文件,代表 Lee 牛仔褲皮夾克的不同版本。其中一件夾克是棕色的,一件是黑色的,最後一件是藍色的。

    [
      {
        "id": 1,
        "description": "Leather jacket",
        "brand": "Lee jeans",
        "color": "brown",
        "product_id": "123456"
      },
      {
        "id": 2,
        "description": "Leather jacket",
        "brand": "Lee jeans",
        "color": "black",
        "product_id": "123456"
      },
      {
        "id": 3,
        "description": "Leather jacket",
        "brand": "Lee jeans",
        "color": "blue",
        "product_id": "123456"
      }
    ]
    

    預設情況下,搜尋 lee leather jacket 會傳回所有三個文件。這可能不是您想要的,因為顯示同一個項目的幾乎相同的變體可能會使結果看起來雜亂無章。

    在這種情況下,您可能只想傳回一個 product_id 對應於此 Lee 牛仔褲皮夾克的文件。若要執行此操作,您可以將 product_id 設定為 distinctAttribute

    curl \
      -X PUT 'https://127.0.0.1:7700/indexes/jackets/settings/distinct-attribute' \
      -H 'Content-Type: application/json' \
      --data-binary '"product_id"'

    藉由將 distinctAttribute 設定為 product_id,搜尋請求**永遠不會傳回多個具有相同 product_id 的文件**。

    在如上所示設定獨特屬性後,查詢 lee leather jacket 只會傳回找到的第一個文件。回應會如下所示

    {
      "hits": [
        {
          "id": 1,
          "description": "Leather jacket",
          "brand": "Lee jeans",
          "color": "brown",
          "product_id": "123456"
        }
      ],
      "offset": 0,
      "limit": 20,
      "estimatedTotalHits": 1,
      "processingTimeMs": 0,
      "query": "lee leather jacket"
    }
    

    如需有關獨特屬性的更深入資訊,請參閱API 參考

    在搜尋時設定獨特屬性

    distinct 是一個您可以新增至任何搜尋查詢的搜尋參數。它可讓您根據內容選擇性地使用獨特屬性。distinct 的優先順序高於 distinctAttribute

    若要搭配 distinct 使用屬性,請先將其新增至 filterableAttributes 清單

    curl \
      -X PUT 'https://127.0.0.1:7700/indexes/products/settings/filterable-attributes' \
      -H 'Content-Type: application/json' \
      --data-binary '[
        "product_id",
        "sku",
        "url"
      ]'

    然後在搜尋查詢中使用 distinct,並指定其中一個已設定的屬性

    curl \
      -X POST 'https://127.0.0.1:7700/indexes/products/search' \
      -H 'Content-Type: application/json' \
      --data-binary '{
        "q": "white shirt",
        "distinct": "sku"
      }'