Yield/add search term to ElasticSearch results

情到浓时终转凉″ 提交于 2021-01-29 08:01:31

问题


I'm doing a ElasticSearch query with multiple terms constructed dynamically, so it looks like this:

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

everything works fine, but I'd like to add to each result, the term that it had match with, so, if for instance the result #1 matched term_a, I'd like somehow to be able to get that term from the current result, something like this:

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

As an example, is there a possibility to do this with Elasticsearch? I could do it with Ruby by mapping the results, but maybe there's another way to do it.


回答1:


Under the current constellation, no. But since the terms query is effectively a bunch of bool-shoulds we can take advantage of named queries like so:

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

yielding

[
  {
    "_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"
    ]
  }
]


来源:https://stackoverflow.com/questions/64249513/yield-add-search-term-to-elasticsearch-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!