Sagi Mann
Sagi Mann

Reputation: 3610

ElasticSearch: return some text surrounding a match on a full-text query?

I have some full text search query on an article index:

  "query": {
    "multi_match": {
      "query": article,
      "fields": [ "text" ],
      "minimum_should_match": "75%"
    }
  }

I want to know if I can change it to return only part of the text rather than the entire matched text. For example, let's say I search for "brown fox". Instead of returning the entire article, I just want to return a few words surrounding any match of "brown fox", so that a result might be ".. is said that any brown fox could jump over fences..", disregarding newlines.

Is this possible in ES?

Upvotes: 2

Views: 2858

Answers (1)

Cnf271
Cnf271

Reputation: 322

As @Adam-t mentioned, highlighting in EC is the key to this answer. For future references I have added my search query where I was able to get the requested answer. I'm posting this answer because, I've also faced the same issue and it took me a while to find a proper solution.

{
   "query":{
      "match_phrase":{
         "text":"investors"
      }
   },
   "highlight":{
      "fragment_size":100,
      "fields":{
         "text":{}
      }
   }
}

Above search query will search for term "investors" through a large text and returns a response like below,

"highlight" : {
     "content" : [
          "*stocks closed at a near three-week high on Wednesday, led by blue-chips, but foreign <em>investors</em>",
          "The dollar currency ended weaker. ** Local <em>investors</em> picked up select shares, with one of the two presidential"
      ]
  }

fragment_size highlights the surrounding text with a default value of 100

Upvotes: 4

Related Questions