一尘不染

elasticsearch-标记强度(嵌套/子文档增强)

elasticsearch

给定一个流行的示例,该示例具有一个标签集合,假设我们希望每个标签都不仅仅是一个字符串,而是一个字符串的元组和一个表示该标签强度的双精度型。

一个查询如何根据标签强度的总和发布和评分(假设我们正在标签名称中搜索确切的字词)


阅读 262

收藏
2020-06-22

共1个答案

一尘不染

可以通过将标签作为嵌套文档建立索引,然后将嵌套查询与自定义分数查询结合使用来完成。在下面的示例中,字词查询找到匹配的标签,自定义分数查询使用“标签”文档的“重量”字段的值作为分数,而嵌套查询使用这些分数的总和作为顶级文档的最终分数。

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
2020-06-22