Yield/add 搜索词到 ElasticSearch 结果

Yield/add search term to ElasticSearch results

我正在使用动态构建的多个术语执行 ElasticSearch 查询,所以它看起来像这样:

...
must: [
  { terms: { tags_slug: ['term_a', 'term_b'] } },
  ...
]
...

一切正常,但我想在每个结果中添加它匹配的术语,因此,例如,如果结果 #1 匹配 term_a,我想以某种方式能够从当前结果中得到那个词,像这样:

Model.search(...).results[0].matched_term # => 'term_a'
Model.search(...).results[1].matched_term # => 'term_b'

举个例子,有没有可能用 Elasticsearch 做到这一点?我可以用 Ruby 通过映射结果来做到这一点,但也许还有另一种方法可以做到这一点。

现在的星座,没有。但是由于 terms 查询实际上是一堆 bool-shoulds 我们可以像这样利用 named queries

{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "tags_slug": {
              "_name": "term_a",
              "value": "term_a"
            }
          }
        },
        {
          "term": {
            "tags_slug": {
              "_name": "term_b",
              "value": "term_b"
            }
          }
        }
      ]
    }
  }
}

屈服

[
  {
    "_index":"tags",
    "_type":"_doc",
    "_id":"s0tOBHUBeQiv5rwb5JPA",
    "_score":0.6931472,
    "_source":{
      "tags_slug":"term_a"
    },
    "matched_queries":[        <---
      "term_a"
    ]
  },
  {
    "_index":"tags",
    "_type":"_doc",
    "_id":"tEtPBHUBeQiv5rwbAZPt",
    "_score":0.6931472,
    "_source":{
      "tags_slug":"term_b"
    },
    "matched_queries":[       <---
      "term_b"
    ]
  }
]