0

I'm trying to prioritize records that have a primary category, over those that have a secondary category, I've found this page

https://www.elastic.co/guide/en/elasticsearch/guide/1.x/query-time-boosting.html and It's a basic example I'm not able to use for my self.

My working query:

{  
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "should": [
            [
              {
                "term": {
                  "primaryCategory": "grocery"
                }
              },
              {
                "term": {
                  "categoryIds": "grocery"
                }
              }
            ]
          ]
        }
      }
    }
  },
  "size": 30,
  "from": 0
}

This returns the results mixed, I'd prefer all things with the primary category to appear first (e.g. grocery before kitchenware)

Here's my failed attempt at doing this

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "should": [
            [
              {
                "term": {
                  "primaryCategory": {
                    "query": "grocery",
                    "boost": 1.5
                  }
                }
              },
              {
                "term": {
                  "categoryIds": {
                    "query": "grocery",
                    "boost": 1
                  }
                }
              }
            ]
          ]
        }
      }
    }
  },
  "size": 30,
  "from": 0
}
Moak
  • 12,596
  • 27
  • 111
  • 166

1 Answers1

2

One way to achieve this is to use dis_max query along with constant score.

Example:

{
   "query": {
      "dis_max": {
         "queries": [
            {
               "constant_score": {
                  "filter": {
                     "term": {
                        "primaryCategory": "grocery"
                     }
                  },
                  "boost": 1.5
               }
            },
            {
               "constant_score": {
                  "filter": {
                     "term": {
                        "categoryIds": "grocery"
                     }
                  },
                  "boost": 1
               }
            }
         ]
      }
   },
   "size": 30,
   "from": 0
}

You could also use a simple bool-query wrapping should-clauses in constant score as above.

keety
  • 17,231
  • 4
  • 51
  • 56