ElasticSearch:基于字段值的条件过滤器

时间:2016-04-21 08:15:50

标签: elasticsearch

这个任务听起来很简单: 如果document field等于特定值,则添加filter,否则不应用filter。

F.X。从仓库中获取所有水果,但如果fruit.type是苹果,请在7天前送到它们。

弹性水平可以吗?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

可以在elassticsearch中使用Nesting Boolean Queriesrange - 糖和date-math - 魔法进行此操作。

由于您没有发布您的地图或一​​些示例数据,我将使用以下数据:

curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "orange", "delivered" : "2016-04-22"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "banana", "delivered" : "2016-03-22"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "orange", "delivered" : "2016-04-12"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "apple", "delivered" : "2016-04-12"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "apple", "delivered" : "2016-04-20"}'

然后以下查询将执行您想要的操作:

curl -XGET "http://localhost:9200/testing/foo/_search" -d'
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {
              "bool": {
                "must_not": {
                  "term": {
                    "fruit": "apple"
                  }
                }
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "term": {
                      "fruit": "apple"
                    }
                  },
                  {
                    "range": {
                      "delivered": {
                        "lt": "now-7d"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}'

在SQL中,这大致转换为:

WHERE fruit <> 'apple' OR (fruit = 'apple' AND delivered < Now-7d)
相关问题