这对我有用,是你需要的吗?
我的解决方案stores the token count on indexing using the token_count datatype. 不是在查询中获取令牌计数(使用tk_count 聚合,如另一个答案中所建议的那样),以便我可以在查询结果中返回“name.stored_length”值。
token_count 是一个“多字段”,它一次只能处理一个字段(即“名称”字段或“正文”字段)。我将示例稍微修改为 store "name.stored_length"
请注意,在我的示例中,它确实不计算令牌的基数(即不同的值),它计算总令牌; “John John Doe”中有 3 个标记; "name.stored_length"===3; (即使它的计数不同的标记只有 2)。注意我要求具体的"stored_fields" : ["name.stored_length"]
最后,您可能需要重新更新您的文档(即发送PUT),或任何技术来获得您想要的值!在这种情况下,我PUT“John John Doe”,即使它在 elasticsearch 中已经是POST/PUT;直到PUT 再次,在将令牌添加到映射之后,令牌才被计算在内。!)
PUT test_token_count
{
"mappings": {
"_doc": {
"properties": {
"name": {
"type": "text",
"fields": {
"stored_length": {
"type": "token_count",
"analyzer": "standard",
//------------------v
"store": true
}
}
}
}
}
}
}
PUT test_token_count/_doc/1
{
"name": "John John Doe"
}
现在我们可以查询或搜索结果,并将结果配置为包含name.stored_length 字段(它既是多字段又是存储字段!):
GET/POST test_token_count/_search
{
//------------------v
"stored_fields" : ["name.stored_length"]
}
并且搜索结果应包括令牌总数为named.stored_length...
{
...
"hits": {
...
"hits": [
{
"_index": "test_token_count",
"_type": "_doc",
"_id": "1",
"_score": 1,
"fields": {
//------------------v
"name.stored_length": [
3
]
}
}
]
}
}