如何在 elasticsearch 查询中对具有不同值的同一字段应用 OR 过滤器
How to apply a OR filter on same field with different values in elasticsearch query
我希望在具有不同值的同一字段上添加过滤器。
基本上我想获得带有 mode1 或 mode2 类型过滤器的文档。以下查询有问题。
{
"index": "abcdef*",
"from": 0,
"size": 50,
"body": {
"query": {
"bool": {
"must": [{ "term": { "id": "123455" } }],
"filter": [{ "term": { "mode": "mode1" } }, { "term": { "mode": "mode2" } }]
}
}
}
}
您需要将 bool/should
子句与 filter
子句一起使用
{
"query": {
"bool": {
"must": [
{
"term": {
"id": "123455"
}
}
],
"filter": [
{
"bool": {
"should": [
{
"term": {
"mode": "mode1"
}
},
{
"term": {
"mode": "mode2"
}
}
]
}
}
]
}
}
}
您可以尝试使用嵌套的 bool 查询并应用 should 子句,其作用类似于 OR 查询。
{
"index": "abcdef*",
"from": 0,
"size": 50,
"body": {
"query": {
"bool": {
"must": [
{
"term": {
"id": "123455"
}
}
],
"filter": [
{
"bool": {
"should": [
{
"term": {
"mode": "mode1"
}
},
{
"term": {
"mode": "mode2"
}
}
]
}
}
]
}
}
}
}
最好将 bool/should
移动到顶层,并使用 bool/filter
而不是 bool/must
来进行术语查询(因为您不需要相关性,只需 yes/no id
字段约束的答案):
{
"query": {
"bool": {
"minimum_should_match": 1,
"should": [
{
"term": {
"mode": "mode1"
}
},
{
"term": {
"mode": "mode2"
}
}
],
"filter": [
{
"term": {
"id": "123455"
}
}
]
}
}
}
或者更好的是,只需利用 terms
查询即可使查询尽可能简单:
{
"query": {
"bool": {
"filter": [
{
"term": {
"id": "123455"
}
},
{
"terms": {
"mode": ["mode1", "mode2"]
}
}
]
}
}
}
我希望在具有不同值的同一字段上添加过滤器。 基本上我想获得带有 mode1 或 mode2 类型过滤器的文档。以下查询有问题。
{
"index": "abcdef*",
"from": 0,
"size": 50,
"body": {
"query": {
"bool": {
"must": [{ "term": { "id": "123455" } }],
"filter": [{ "term": { "mode": "mode1" } }, { "term": { "mode": "mode2" } }]
}
}
}
}
您需要将 bool/should
子句与 filter
子句一起使用
{
"query": {
"bool": {
"must": [
{
"term": {
"id": "123455"
}
}
],
"filter": [
{
"bool": {
"should": [
{
"term": {
"mode": "mode1"
}
},
{
"term": {
"mode": "mode2"
}
}
]
}
}
]
}
}
}
您可以尝试使用嵌套的 bool 查询并应用 should 子句,其作用类似于 OR 查询。
{
"index": "abcdef*",
"from": 0,
"size": 50,
"body": {
"query": {
"bool": {
"must": [
{
"term": {
"id": "123455"
}
}
],
"filter": [
{
"bool": {
"should": [
{
"term": {
"mode": "mode1"
}
},
{
"term": {
"mode": "mode2"
}
}
]
}
}
]
}
}
}
}
最好将 bool/should
移动到顶层,并使用 bool/filter
而不是 bool/must
来进行术语查询(因为您不需要相关性,只需 yes/no id
字段约束的答案):
{
"query": {
"bool": {
"minimum_should_match": 1,
"should": [
{
"term": {
"mode": "mode1"
}
},
{
"term": {
"mode": "mode2"
}
}
],
"filter": [
{
"term": {
"id": "123455"
}
}
]
}
}
}
或者更好的是,只需利用 terms
查询即可使查询尽可能简单:
{
"query": {
"bool": {
"filter": [
{
"term": {
"id": "123455"
}
},
{
"terms": {
"mode": ["mode1", "mode2"]
}
}
]
}
}
}