[英]Elasticsearch 2.x, query for tag, and sort results by tag weigth
我正在使用Elasticsearch 2.3
我有一個書索引。 每本書都有標簽,每個標簽都有重量。 我想獲取所有具有請求標簽的圖書,並按標簽重量排序。
例如:
PUT book/book/0
{
"name": "book 0",
"tags": [
{"t": "comedy", "w": 30},
{"t": "drama","w": 20},
]
}
PUT book/book/1
{
"name": "book 1",
"tags": [
{"t": "comedy", "w": 10},
{"t": "drama","w": 5},
{"t": "other","w": 50},
]
}
PUT book/book/2
{
"name": "book 2",
"tags": [
{"t": "comedy", "w": 5},
{"t": "drama","w": 30},
]
}
PUT book/book/3
{
"name": "book 3",
"tags": [
{"t": "comedy", "w": 5},
{"t": "other","w": 30},
]
}
我想搜索所有帶有喜劇和戲劇標簽的書籍。 結果順序為:
更新:我只想返回匹配兩個標簽的書(並僅按請求的標簽排序)。 因此,如果我搜索“戲劇”和“喜劇”,則只會返回同時具有兩個標簽的書籍(在本例中為書籍0,書籍1,書籍2),並按請求的標簽權重排序。
我怎么能得到這個? 任何查詢的例子嗎?
如果您始終想對所有權重求和,即使對於與查詢不匹配的標記, 易卜拉欣的答案都是正確的。
如果只想考慮要搜索的標簽的權重,則必須將tags
作為nested
對象編制索引。 這是因為,否則一切t
S和w
s的壓扁成列表,在此過程中(描述丟失協會在這里 )。
然后,您可以使用nested
在nested
查詢中的function_score
查詢來僅匯總匹配標記的權重。 您將必須啟用腳本 。
這是一個例子:
GET /book/_search
{
"query": {
"nested": {
"path": "tags",
"query": {
"function_score": {
"query": {
"bool": {
"filter": [
{
"terms": {
"tags.t": [
"comedy",
"drama"
]
}
}
]
}
},
"functions": [
{
"script_score": {
"script": "return doc['tags.w'].value"
}
}
],
"boost_mode": "replace"
}
},
"score_mode": "sum"
}
}
}
如果只返回與兩個標簽都匹配的圖書(在示例中為喜劇和戲劇),則它會變得更加復雜,因為每個搜索詞都需要自己的nested
查詢。
這是一個例子:
GET /book/_search { "query": { "bool": { "must": [ { "nested": { "path": "tags", "query": { "function_score": { "query": { "term": { "tags.t": { "value": "comedy" } } }, "functions": [ { "script_score": { "script": "return doc['tags.w'].value" } } ], "boost_mode": "replace" } } } }, { "nested": { "path": "tags", "query": { "function_score": { "query": { "term": { "tags.t": { "value": "drama" } } }, "functions": [ { "script_score": { "script": "return doc['tags.w'].value" } } ], "boost_mode": "replace" } } } } ] } } }
嘗試這個:
POST book/book/_search
{
"query": {
"match": {
"tags.t": "comedy drama"
}
},
"sort": [
{
"tags.w": {
"order": "desc",
"mode": "sum"
}
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.