rap-2-h
rap-2-h

Reputation: 31948

Search in two fields on elasticsearch with kibana

Assuming I have an index with two fields: title and loc, I would like to search in this two fields and get the "best" match. So if I have three items:

{"title": "castle", "loc": "something"},
{"title": "something castle something", "loc": "something,pontivy,something"},
{"title": "something else", "loc": "something"}

... I would like to get the second one which has "castle" in its title and "pontivy" in its loc. I tried to simplify the example and the base, it's a bit more complicated. So I tried this query, but it seems not accurate (it's a feeling, not really easy to explain):

GET merimee/_search/?
{
  "query": {
    "multi_match" : {
      "query":    "castle pontivy", 
      "fields": [ "title", "loc" ] 
    }
  }
}

Is it the right way to search in various field and get the one which match the in all the fields?

Not sure my question is clear enough, I can edit if required.

EDIT:

The story is: the user type "castle pontivy" and I want to get the "best" result for this query, which is the second because it contains "castle" in "title" and "pontivy" in "loc". In other words I want the result that has the best result in both fields.

Upvotes: 0

Views: 1255

Answers (2)

jmlw
jmlw

Reputation: 91

As the other posted suggested, you could use a bool query but that might not work for your use case since you have a single search box that you want to query against multiple fields with.

I recommend looking at a Simple Query String query as that will likely give you the functionality you're looking for. See: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html

So you could do something similar to this:

{
  "query": {
    "simple_query_string" : {
        "query": "castle pontivy",
        "fields": ["title", "loc"],
        "default_operator": "and"
    }
  }
}

So this will try to give you the best documents that match both terms in either of those fields. The default operator is set as AND here because otherwise it is OR which might not give you the expected results.

It is worthwhile to experiment with other options available for this query type as well. You might also explore using a Query String query as it gives more flexibility but the Simple Query String term works very well for most cases.

Upvotes: 2

Saram Ali Azhar
Saram Ali Azhar

Reputation: 254

This can be done by using bool type of query and then matching the fields.

  GET _search
  {
   "query": 
    {
     "bool": {"must": [{"match": {"title": "castle"}},{"match": {"loc": "pontivy"}}]
    }
   }
  }

Upvotes: 1

Related Questions