Search code examples
elasticsearchelasticsearch-dslelasticsearch-queryelasticsearch-7elasticsearch-php

How can I prioritize documents in Elasticsearch query


I have products in my index. Documents are basically structured like these:

{
    "_id": "product",
    "_source": {
      ...
      "type": "product",
      "id": 1,
      "mainTaxon": {
        "name": "T-SHIRT",
      },
      "attributes": [
        {
          "code": "name",
          "name": "Name",
          "value": [
            "BANANA T-SHIRT"
          ],
          "score": 50
        },
      ]
    }
  },
  {
    "_id": "product",
    "_source": {
      ...
      "type": "product",
      "id": 2,
      "mainTaxon": {
        "name": "JEANS",
      },
      "attributes": [
        {
          "code": "name",
          "name": "Name",
          "value": [
            "BANANA JEANS"
          ],
          "score": 50
        },
      ]
    }
  }
}

When I search for 'BANANA' I would prioritize products with mainTaxon different from JEANS. So, every product with the mainTaxon name T_SHIRT or something else would be listed before products with mainTaxon JEANS.


Solution

  • You can use boosting query to prioritize documents

     {
      "query": {
        "boosting": {
          "positive": {
            "match": {
              "attributes.value": "banana"
            }
          },
          "negative": {
            "match": {
              "mainTaxon.name": "JEANS"
            }
          },
          "negative_boost": 0.5
        }
      }
    }
    

    Search Result will be

    "hits": [
          {
            "_index": "67164768",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.5364054,
            "_source": {
              "type": "product",
              "id": 1,
              "mainTaxon": {
                "name": "T-SHIRT"
              },
              "attributes": [
                {
                  "code": "name",
                  "name": "Name",
                  "value": [
                    "BANANA T-SHIRT"
                  ],
                  "score": 50
                }
              ]
            }
          },
          {
            "_index": "67164768",
            "_type": "_doc",
            "_id": "2",
            "_score": 0.32743764,
            "_source": {
              "type": "product",
              "id": 2,
              "mainTaxon": {
                "name": "JEANS"
              },
              "attributes": [
                {
                  "code": "name",
                  "name": "Name",
                  "value": [
                    "BANANA JEANS"
                  ],
                  "score": 50
                }
              ]
            }
          }
        ]