如何使用 ElasticSearch 应用默认 post 过滤器?

How to apply default post filter with ElasticSearch?

我想使用 elasticsearch 实现一个回测引擎。为了能够做到这一点,我需要通过排除那些比测试日期早 post 的命中来过滤命中,我想默认这样做,因为算法(我想回测)不是应该知道回测。

换句话说,是否可以将默认 post 过滤器应用于 ElasticSearch 查询?

例如,假设这些文档在 ES 中:

{ name: 'Jean', weight: 70, date: 2012-01-01 }
{ name: 'Jules', weight: 70, date: 2010-01-01 }
{ name: 'David', weight: 80, date: 2010-01-01 }

我想应用默认的 post 过滤器来排除 2011 年之前 post 的文档,如果我查询每个权重为 70 的人,唯一的结果我有是朱尔斯。

你可以用 Filtered Aliases 做到这一点。当您通过别名查询时,过滤器会自动应用于您的查询...这会在您的应用程序中隐藏它:

// Insert the data
curl -XPOST "http://localhost:9200/people/data/" -d'
{ "name": "Jean", "weight" : 70, "date": "2012-01-01" }'

curl -XPOST "http://localhost:9200/people/ata" -d'
{ "name": "Jules", "weight" : 70, "date": "2010-01-01" }'

curl -XPOST "http://localhost:9200/people/data/" -d'
{ "name": "David", "weight" : 80, "date": "2010-01-01" }'

// Add a filtered alias
curl -XPOST "http://localhost:9200/_aliases" -d'
{
    "actions" : [
        {
            "add" : {
                 "index" : "people",
                 "alias" : "filtered_people",
                 "filter" : { 
                    "range" : { 
                        "date" : { "gte" : "2011-01-01"} 
                    } 
                }
            }
        }
    ]
}'

现在您针对 filtered_people 而不是基础 people 索引执行搜索:

curl -XGET "http://localhost:9200/filtered_people/_search" -d'
{
    "query": {
        "filtered": {
           "filter": {
               "term": {
                  "weight": 70
               }
           }
        }
    }
}'

其中 return 只是您感兴趣的文档:

{
   "took": 3,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "people",
            "_type": "ata",
            "_id": "AUudZPUfCSiheYJkTW-h",
            "_score": 1,
            "_source": {
               "name": "Jules",
               "weight": 70,
               "date": "2010-01-01"
            }
         }
      ]
   }
}