在 Elasticsearch 中,terms_set
查詢通常用于在一個字段上進行多值匹配,并支持設置一個條件(例如最小匹配數量),讓查詢結果更具靈活性。為了展示如何使用 terms_set
查詢,我們首先會創建一個索引,寫入一些數據,然后演示如何進行查詢。
1. 創建索引和寫入數據
首先,假設我們有一個關于 articles
(文章)的索引,每個文檔包含字段 tags
(標簽),我們希望查詢文檔中的標簽是否包含給定的多個值。
創建索引
假設我們的索引名為 articles
,并且每個文檔包含字段 tags
(多個標簽值)。
PUT /articles
{"mappings": {"properties": {"title": { "type": "text" },"tags": { "type": "keyword" }}}
}
在上述示例中,我們定義了一個名為 articles
的索引,其中 tags
字段是 keyword
類型,因為我們想要存儲和查詢標簽。
寫入數據
接下來,我們寫入一些數據。每個文檔包含文章標題和相關的標簽。
POST /articles/_bulk
{ "index": { "_id": 1 } }
{ "title": "Tech News Today", "tags": ["tech", "news", "AI"] }
{ "index": { "_id": 2 } }
{ "title": "Sports Highlights", "tags": ["sports", "news", "football"] }
{ "index": { "_id": 3 } }
{ "title": "Latest in AI", "tags": ["tech", "aAI"] }
{ "index": { "_id": 4 } }
{ "title": "Football Updates", "tags": ["sports", "football"] }
{ "index": { "_id": 5 } }
{ "title": "Tech Innovations", "tags": ["tech", "innovation"] }
在這個例子中,我們為不同的文章指定了多個標簽,如 tech
、sports
、news
、AI
等。
2. 使用 terms_set
查詢
現在,我們將使用 terms_set
查詢來查找至少匹配給定標簽集的文檔。比如,我們希望找到那些標簽字段中至少包含 tech
、news
、AI
中的兩個標簽的文檔。
查詢示例
POST /articles/_search
{"query": {"terms_set": {"tags": {"terms": ["tech", "news", "AI"],"minimum_should_match_script": {"source": "Math.min(params.num_terms, 2)"}}}}
}
解釋:
terms_set
: 查詢的目標字段是tags
。terms
: 這里列出的是我們要匹配的標簽集合:["tech", "news", "AI"]
。minimum_should_match_script
: 使用腳本來設置條件,要求文檔的tags
字段至少包含集合中的兩個標簽。Math.min(params.num_terms, 2)
的意思是,“返回包含至少兩個標簽的文檔”。
3. 查詢結果
假設查詢成功執行,以下是結果:
{"took" : 13,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 1,"relation" : "eq"},"max_score" : 3.810946,"hits" : [{"_index" : "articles","_type" : "_doc","_id" : "1","_score" : 3.810946,"_source" : {"title" : "Tech News Today","tags" : ["tech","news","AI"]}}]}
}
在這個結果中,符合查詢條件的文檔是:
- 文檔 1:
tags
包含tech
、news
、AI
,至少包含兩個標簽。 - 文檔 3:
tags
包含tech
、AI
,至少包含兩個標簽。
5. 總結
terms_set
查詢在處理多值字段時非常有用,特別是當你希望在一個字段中匹配多個值,并且可以靈活控制匹配條件時。terms
參數用于指定查詢的多個值,minimum_should_match_script
則用于自定義最小匹配數量。- 這種查詢方法非常適合需要對多值條件進行動態調整的情況,比如在推薦系統或復雜篩選條件下使用。