George Edwards
George Edwards

Reputation: 9229

Multi-field search in the elasticsearch-js library

I am using elasticsearch (managed instance from searchly) with the elasticsearch-js npm client library. I want to search multiple fields in my index from a term. There seems to be loads of documentation on this, e.g.

GET /_search
{
  "query": {
    "bool": {
      "should": [
        { "match": { "title":  "War and Peace" }},
        { "match": { "author": "Leo Tolstoy"   }}
      ]
    }
  }
}

where I could just set the same value for author and title. However, this is a get request and is structured differently to the nodejs library, where I am doing this:

this._client.search({
  index: 'sample',
  body: {
    query: {
      match: {
        name: 'toFind'
      }
    }
  }
}).then(function (resp) {
  var hits = resp.hits.hits;
}, function (err) {
  console.trace(err.message);
});

I can't have multiple match: fields otherwise tsc complains about strict mode, and if I try something like:

    query: {
      match: {
        name: 'toFind',
        description: 'toFind'
      }
    }

then I get an error:

"type": "query_parsing_exception",

"reason": "[match] query parsed in simplified form, with direct field name, but included more options than just the field name, possibly use its \u0027options\u0027 form, with \u0027query\u0027 element?",

Upvotes: 1

Views: 3219

Answers (1)

ChintanShah25
ChintanShah25

Reputation: 12672

Since you want to match same string on multiple fields you need multi match query. Try something like this

this._client.search({
  index: 'sample',
  body: {
    query: {
      multi_match: {
        query: 'toFind',
        fields: ['name','description']
      }
    }
  }
}).then(function (resp) {
  var hits = resp.hits.hits;
}, function (err) {
  console.trace(err.message);
});

Upvotes: 8

Related Questions