Home > database >  Elasic search: find doc by id and highlight words based on query string
Elasic search: find doc by id and highlight words based on query string

Time:07-29

I like to find an document in elastic search an highlight terms based on an query string. Is this possible? I tried to run an query-string elastic search and filter the result based on ID. But those sounds not very efficient, because elastic first generates an huge list of all document matched the querystring (which could by millions) an pic only one document based on the filter.

Is there a way or query-contstruct to combine querystring and "search for term in _id field" in one boolean search?

Something like this (which is not working):

"query": {
    "bool": {
        "must": {
            "query_string": {
                "query": "red*",
                "fields": [
                    "text",
                    "title"
                ] 
            },
            "term": {
                "_id":"fda72434fa172"
            }
        }
    }
},
"highlight": {
  "fields": {
[...]

CodePudding user response:

I made a small example that can be a starting point. Use filter to perform your query and retrieve the doc by id. Then I used match and highlight to highlight the term I want.

POST test/_doc/fda72434fa172
{
  "text": "I like to find an document in elastic search an highlight terms based on an query string. Is this possible?"
}

GET test/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "_id": "fda72434fa172"
          }
        }
      ],
      "must": [
        {
          "match": {
            "text": {
              "query": "elastic search"
            }
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "text": {}
    }
  }
}
  • Related