Search elasticity - tagging (attached / child documents)

Given a popular example of a message with a collection of tags, let's say that we want each tag to be larger than the string, but a tuple of the string and double, which means the strength of the specified tag.

How to request messages and evaluate them based on the sum of strong tags (suppose we are looking for exact terms in tag names)

+2
source share
1 answer

This can be done by specifying tags as subdocuments , and then using nested in conjunction with a custom score query. In the example below, the terms “query” detect matching tags, a custom rating query uses the “wight” field from the “tags” of documents as points, and a sub-query uses the sum of these ratings as the final rating for the top-level document.

curl -XDELETE 'http://localhost:9200/test-idx' echo curl -XPUT 'http://localhost:9200/test-idx' -d '{ "mappings": { "doc": { "properties": { "title": { "type": "string" }, "tags": { "type": "nested", "properties": { "tag": { "type": "string", "index": "not_analyzed" }, "weight": { "type": "float" } } } } } } }' echo curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '{ "title": "1", "tags": [{ "tag": "A", "weight": 1 }, { "tag": "B", "weight": 2 }, { "tag": "C", "weight": 4 }] } ' echo curl -XPUT 'http://localhost:9200/test-idx/doc/2' -d '{ "title": "2", "tags": [{ "tag": "B", "weight": 2 }, { "tag": "C", "weight": 3 }] } ' echo curl -XPUT 'http://localhost:9200/test-idx/doc/3' -d '{ "title": "3", "tags": [{ "tag": "B", "weight": 2 }, { "tag": "D", "weight": 4 }] } ' echo curl -XPOST 'http://localhost:9200/test-idx/_refresh' echo # Example with custom script (slower but more flexable) curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true' -d '{ "query" : { "nested": { "path": "tags", "score_mode": "total", "query": { "custom_score": { "query": { "terms": { "tag": ["A", "B", "D"], "minimum_match" : 1 } }, "script" : "doc['\''weight'\''].value" } } } }, "fields": [] }' echo 
+8
source

Source: https://habr.com/ru/post/1500753/


All Articles