[英]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.