[英]How to use OR in a filtered query with Elasticsearch 2.x
我正在使用Elasticsearch 2.4,並且嘗試獲取行為類似於以下SQL語句的查詢:
SELECT * FROM countries WHERE continent='Europe' and (country='Andorra' OR cities in ['Madrid'])
在Elasticsearch 1.5中,我使用以下查詢使其工作:
{
"query": {
"filtered": {
"filter": {
"term": {
"continent": "Europe"
}
},
"query": {
"bool": {
"should": [
{
"nested": {
"path": "cities",
"query": {
"match": {
"cities.name": "Madrid"
}
}
}
},
{
"match": {
"country": "Andorra"
}
}
]
}
}
}
}
}
但是似乎在2.x版本中, 不推薦使用 “過濾”參數。 我嘗試使用使用filter的新方法來構建查詢,但是它找不到正確的嵌套值 。 這是結果查詢:
{
"query": {
"bool": {
"filter": [
{
"term": {
"continent": "Europe"
}
}
],
"should": [
{
"nested": {
"path": "cities",
"query": {
"match": {
"cities.name": "Madrid"
}
}
}
},
{
"match": {
"country": "Andorra"
}
}
]
}
}
}
這是我要獲取的數據:
{
"_index":"countries",
"_type":"item",
"_id":"123",
"_version":1,
"found":true,
"_source":{
"country": "Spain",
"cities": [
{
"id_city": 2133,
"name": "Madrid"
},
{
"id_city": 8382,
"name": "Barcelona"
}
]
}
}
有人知道實現此目標的正確方法嗎?
查看是否可行:
{
"query" : {
"bool" : {
"should" : [{
"nested" : {
"path" : "cities",
"query" : {
"match" : {
"cities.name" : "Madrid"
}
}
}
}, {
"match" : {
"country" : "Spain"
}
}
],
"filter" :
[{
"term" : {
"continent" : "Europe"
}
}
]
}
}
}
其實我是這樣工作的:
{
"query": {
"bool": {
"filter": [
{
"term": {
"continent": "Europe"
}
}
],
"must": [
{
"bool": {
"should": [
{
"nested": {
"path": "cities",
"query": {
"match": {
"cities.name": "Madrid"
}
}
}
},
{
"match": {
"country": "Andorra"
}
}
]
}
}
]
}
}
}
我知道..很奇怪,但是如果查詢與主查詢中使用“應該”而不是“必須”的任何術語都不匹配,則會從Europe
返回很多隨機結果。
如果您的bool
查詢具有filter
或must
子句,則should
子句不需要具有任何匹配項即可獲取結果。 如果是獨立的,則需要具有1個匹配項。 在文檔中, 網址為: https : //www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html
因此,嘗試一下,並使用"minimum_should_match": 1
強制至少匹配"minimum_should_match": 1
。
{
"query": {
"bool": {
"filter": [
{
"term": {
"continent": "Europe"
}
}
],
"should": [
{
"nested": {
"path": "cities",
"query": {
"match": {
"cities.name": "Madrid"
}
}
}
},
{
"match": {
"country": "Andorra"
}
}
],
"minimum_should_match": 1
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.