所以我有一個 ES 檔案,我無法控制其結構,所以我無法更改映射。我有一個由 ES“分析”的location欄位(映射型別text)。我的檔案是這樣的:
[
{
title: "Something that happened in the UK",
location: "United States, London"
},
{
title: "Something that happened in the US",
location: "United Kingdom, London"
}
]
我正在嘗試撰寫一個查詢,該查詢只會過濾該location欄位并回傳兩者之一united states或united kingdom但不是兩者的結果。
{
"query":
{
"match": {
"location": { "query": "united statess" }
}
}
這不起作用,因為該詞united出現在兩個位置名稱中。不幸的是,該欄位已被分析,它將回傳兩個結果。我曾嘗試將"operator" : "and"加到“匹配”查詢中,但沒有回傳任何結果。我錯過了什么?有沒有辦法通過“匹配”查詢來實作這一點?
uj5u.com熱心網友回復:
我了解到您正在嘗試在 location 欄位上創建 xor 過濾器。Elasticsearch 的布爾查詢中沒有 xor 快捷方式,但可以使用 OR、AND 和 NOT 運算子構造 xor。
必須 -> 并且
應該 -> 或
must_not -> 不
所以有兩種方法可以用這些運算子(偽代碼)構造一個異或過濾器:
must( (should(uk, us), must_not( must(uk, us))
should( must( uk, must_not(us)), must(must_not(uk), us))
還有更易讀的Query_String 查詢,它支持布爾語法。
下面是 bool 和 match 查詢組合的示例以及作為異或的查詢字串查詢的示例,您可以在 Kibana 開發工具中測驗這些查詢:
PUT /test_xor
PUT /test_xor/_doc/1
{
"type": "neither uk nor us",
"location": [
{
"title": "Something that happened in germany",
"location": "Germany, Berlin"
},
{
"title": "Something that happened in the France",
"location": "France, Paris"
}
]
}
PUT /test_xor/_doc/2
{
"type": "only us",
"location": [
{
"title": "Something that happened in germany",
"location": "Germany, Berlin"
},
{
"title": "Something that happened in the US",
"location": "United States, London"
}
]
}
PUT /test_xor/_doc/3
{
"type": "only uk",
"location": [
{
"title": "Something that happened in germany",
"location": "Germany, Berlin"
},
{
"title": "Something that happened in the US",
"location": "United States, London"
}
]
}
PUT /test_xor/_doc/4
{
"type": "uk and us",
"location": [
{
"title": "Something that happened in the US",
"location": "United States, London"
},
{
"title": "Something that happened in the UK",
"location": "United Kingdom, London"
}
]
}
GET /test_xor/_search
{
"query": {
"query_string" : {
"query": "(\"United States, London\" OR \"United Kingdom, London\") AND NOT (\"United States, London\" AND \"United Kingdom, London\")",
"fields": ["location.location"]
}
}
}
GET /test_xor/_search
{
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"match": {
"location.location": {
"query": "United States, London",
"operator": "and"
}
}
},
{
"match": {
"location.location": {
"query": " OR \"United Kingdom, London\"",
"operator": "and"
}
}
}
]
}
},
{
"bool": {
"must_not": [
{
"bool": {
"must": [
{
"match": {
"location.location": {
"query": "United States, London",
"operator": "and"
}
}
},
{
"match": {
"location.location": {
"query": "United Kingdom, London",
"operator": "and"
}
}
}
]
}
}
]
}
}
]
}
}
}
uj5u.com熱心網友回復:
在嘗試了各種事情之后,我想出了這個似乎有效的解決方案。盡管出于某種原因,我覺得有更好的方法來實作這一目標:
回答我自己的問題,這有意義嗎???
{
"query": {
"bool": {
"must": [
{
"match": {
"location": "united"
}
},
{
"match": {
"location": "states"
}
}
]
}
}
}
[編輯]:我實際上找到了一個更好的解決方案,如下所示:
{
"query": {
{
"match_phrase": {
"location": "united states"
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330905.html
標籤:弹性搜索
