pythonelasticsearchpyelasticsearch

Elastic Search Function_Score Query with Query_String


I was doing search using elastic search using the code:

es.search(index="article-index", fields="url", body={
  "query": {
    "query_string": {
      "query": "keywordstr",
      "fields": [
        "text",
        "title",
        "tags",
        "domain"
      ]
    }
  }
})

Now I want to insert another parameter in the search scoring - "recencyboost".

I was told function_score should solve the problem

res = es.search(index="article-index", fields="url", body={
  "query": {
    "function_score": {
      "functions": {
        "DECAY_FUNCTION": {
          "recencyboost": {
            "origin": "0",
            "scale": "20"
          }
        }
      },
      "query": {
        {
          "query_string": {
            "query": keywordstr
          }
        }
      },
      "score_mode": "multiply"
    }
  }
})

It gives me error that dictionary {"query_string": {"query": keywordstr}} is not hashable.

1) How can I fix the error?

2) How can I change the decay function such that it give higher weight to higher recency boost?


Solution

  • You appear to have an extra query in your search (giving a total of three), which is giving you an unwanted top-level. You need to remove the top-level query and replace it with function_score as the top level key.

    res = es.search(index="article-index", fields="url", body={"function_score": {
        "query": {
            { "query_string": {"query": keywordstr} }
        },
        "functions": {
            "DECAY_FUNCTION": {
                "recencyboost": {
                    "origin": "0",
                    "scale": "20"
                }
            }
        },
        "score_mode": "multiply"
    })
    

    Note: score_mode defaults to "multiply", as does the unused boost_mode, so it should be unnecessary to supply it.