Search code examples
elasticsearchscoring

Elasticsearch: Having document score equal number of hits in field


Using elasticsearch, I'm searching through an index on a field that typically has a large amount of text and I simply want to know the number of times the query was matched per document. Anyone know of a good way to do this? I'd like to do it through the score value if possible. So for example, if I searched "fox" on "the quick brown fox jumped over the lazy fox", I'd get something that includes:

"_score" : 2.0


Solution

  • The default scoring model also account this into picture , but then this is not the only thing accounts. What you are looking for is called term frequency. The default scoring model is based on TF-IDF ( Term frequency and inverse document frequency) and also field length. You can read more about it here.

    Now coming back to your requirement , you can use the scripting module and function score query

    {
      "query": {
        "function_score": {
          "query": {
            "match": {
              "field": "fox"
            }
          },
          "boost_mode": "replace",
          "functions": [
            {
              "script_score": {
                "script": "_index['field']['fox'].tf()"
              }
            }
          ]
        }
      }
    }