Home > other >  Prioretized field OR query in elasticsearch
Prioretized field OR query in elasticsearch

Time:02-21

I would like to know solution for my problem:

Let's say I have a artistId and songId in my Elasticsearch document.

I want to query documents like this:

If possible, query with songId with term query, but if there are no matches result with that given songId, I want to query with artistId. The logic is here I want to make is prioretized query for songId. This scores should be higher than artistId. Match with the same songId! If there are not any same songId in my query result, I can query again with the artistId. But I am not able to find the solution without 2 queries.

I want to make it applied with just one query, is it possible with elasticsearch query?

I have found multi match query:

{
  "multi_match" : {
    "query":    "songId12345", 
    "fields": [ "songId^3", "artistId" ] 
  }
}

With this query, my songId is prioritized but I can not give to my query the same value for bot songId and artistId value for: songId12345 my artistId value must differ than songId. May be I can keep the value with new field like

mixedField: songId - artistId

but it should not work exactly too.

summary: find me same songId, if my query does return any value, find me with same artistId and doing this with exactly 1 query

Any idea? Thanks for your time.

CodePudding user response:

One way here is to use a boolean query and combine your queries using a should clause.

Further, you need to boost the songId clause. The query would go something like this:

{
   "query": {
      "bool": {
         "should": [
            {
               "match": {
                  "songId": {
                     "query": "song123",
                     "boost": 2
                  }
               }
            },
            {
               "match": {
                  "artistId": {
                     "query": "artist123"
                  }
               }
            }
         ]
      }
   }
}

Read the full article here

  • Related