Home > database >  How to extract matching groups when searching regex in elasticsearch
How to extract matching groups when searching regex in elasticsearch

Time:07-22

Am using elasticsearch to index some data (a text article) and mapped it as

"article": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          }

, then I use regexp queries to search for some matches, the result returns the correct documents, but is there a way to also return the matching groups/text which triggered the regex hit ?

CodePudding user response:

You can use highlghting functionality of Elasticsearch.

Lets consider below is your sample document:

{
  "article":"Elasticsearch Documentation"
}

Query:

{
  "query": {
    "regexp": {
      "article": "el.*ch"
    }
  },
  "highlight": {
    "fields": {
      "article": {}
    }
  }
}

Response

{
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "cHzAH4IBgPd6xUeLm9QF",
        "_score" : 1.0,
        "_source" : {
          "article" : "Elasticsearch Documentation"
        },
        "highlight" : {
          "article" : [
            "<em>Elasticsearch</em> Documentation"
          ]
        }
      }
  • Related