Home > OS >  Custom ordering on elastic search
Custom ordering on elastic search

Time:02-12

I'm executing a simple query which returns items matched by companyId.

In addition to only showing clients matching a specific company I also want records matching a certain location to appear at the top.So if somehow I pass through pseudo sort:"location=Johannesburg" it would return the data below and items which match the specific location would appear on top, followed by items with other locations.

Data:

{
  "clientId" : 1,
  "clientName" : "Name1",
  "companyId" : 8,
  "location" : "Cape Town"
},
{
  "clientId" : 2,
  "clientName" : "Name2",
  "companyId" : 8,
  "location" : "Johannesburg"
}

Query:

 {
      "query": {
        "match": {
          "companyId": "8"
        }
      },
      "size": 10,
      "_source": {
        "includes": [
          "firstName",
          "companyId",
          "location"
        ]
      }
    }

Is something like this possible in elastic and if so what is the name of this concept?(I'm not sure what to even Google for to solve this problem)

CodePudding user response:

It can be done in different ways. Simplest (if go only with text matching) is use bool query with should statement.

The bool query takes a more-matches-is-better approach, so the score from each matching must or should clause will be added together to provide the final _score for each document. Doc

Example:

{"query":
   "bool": {
     "must": [
        "match": {
          "companyId": "8"
        }
      ],
     "should": [
        "match": {
          "location": "Johannesburg"
         }
      ]
     }
   }
}

More complex solution is to store GEO points in location, and use Distance feature query as example.

  • Related