multi indices Elasticsearch query in golang

345 Views Asked by At

Hy, I am facing problem during creation of search query for multi indices in Elasticsearch. I have two indices one is "files" having field "filename" and other indices is "message" having field "messageid".I want to get result base on both indices where filename="any stored name in els" from files indices and messageid="any store id in ELS". I want this search in single query.

trying to search ELS query base on multi indices.

1

There are 1 best solutions below

1
On

The indices in the URL of a search request in elasticsearch specify the indices to search within. You can search within one or more indices by specifying the indices in the URL of the search request.

To search for documents that match a specific phrase in the filename field of the files index or the messageid field of the message index, you can use the match_phrase query within a bool query with a should clause. This allows you to search for documents that match either of the queries, while only returning exact matches for the specified phrases.

Here is an example:

POST /files,message/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "filename": "any stored name in els"
          }
        },
        {
          "match_phrase": {
            "messageid": "any stored id in ELS"
          }
        }
      ]
    }
  }
}

This search request will return all documents that contain the exact phrase "any stored name in els" in the filename field of the files index, or the exact phrase "any stored id in ELS" in the messageid field of the message index.

This is how it can be achieved in Golang:

query := elasticsearch.NewBoolQuery().Should(
    elasticsearch.NewMatchPhraseQuery("filename", "any stored name in els"),
    elasticsearch.NewMatchPhraseQuery("messageid", "any stored id in ELS"),
)

searchResult, err := client.Search().
    Index("files", "message").
    Query(query).
    Do(context.Background())