Cerin
Cerin

Reputation: 64739

How to query Elasticsearch to boost by specific field

How do you index and query documents containing a custom weight so that you can use that weight to promote specific query results?

I've indexed simple documents with bodies like {"text":"how now brown cow", "weight":2.3}.

Using the Python wrapper, I can easily search these by doing:

es = Elasticsearch()
results = es.search(
    index='my_index',
    body={
        'query':{
            'query_string':{
                'query':my_search_terms,
            },
        },
    },
)

However, after reading the docs, I can't figure out how to incorporate the weight field so that results are boosted by this value. How would I do this?

Upvotes: 3

Views: 1535

Answers (1)

femtoRgon
femtoRgon

Reputation: 33341

I believe you can do this with a function_score query

Something like:

{
"query": {
    "function_score": {
        "query": {  
            "match": {
                "text": "how now brown cow"
            }
        },
        "functions": [{
            "script_score": { 
                "script": "doc['weight'].value"
            }
        }],
        "score_mode": "multiply"
    }
}
}

Upvotes: 1

Related Questions