gpt4 book ai didi

elasticsearch - Elasticsearch:每个关键字的前k个结果

转载 作者:行者123 更新时间:2023-12-02 22:57:25 27 4
gpt4 key购买 nike

我们在elasticsearch中有以下文档。

class Query(DocType):
text = Text(analyzer='snowball', fields={'raw': Keyword()})
src = Keyword()

现在我们想要每个 src 的前k个结果。我们怎样才能做到这一点?

示例:-假设我们为以下内容建立索引:
# src: place_order
Query(text="I want to order food", src="place_order")
Query(text="Take my order", src="place_order")
...

# src: payment
Query(text="How to pay ?", src="payment")
Query(text="Do you accept credit card ?", src="payment")
...

现在,如果用户写了一个查询 接受我的订单以及信用卡详细信息 k = 1 ,那么我们应该返回以下两个结果
[{"text": "Take my order", "src": "place_order", }, 
{"text": "Do you accept credit card ?", "src": "payment"}
]

由于k = 1,因此对于每个src我们只返回一个结果。

最佳答案

您可以尝试top hits聚合,它将在聚合中每个存储桶中返回前N个匹配的文档。

对于您帖子中的示例,查询可能如下所示:

POST queries/query/_search
{
"query": {
"match": {
"text": "take my order please along with the credit card details"
}
},
"aggs": {
"src types": {
"terms": {
"field": "src"
},
"aggs": {
"best hit": {
"top_hits": {
"size": 1
}
}
}
}
}
}

文本查询上的搜索限制了用于聚合的文档集。 "src types"聚合将在匹配文档中找到的所有 src值分组,并且 "best hit"每个存储桶选择一个最相关的文档(可以根据需要更改 size参数)。

查询结果将如下所示:
{
"hits": {
"total": 3,
"max_score": 1.3862944,
"hits": [
{
"_index": "queries",
"_type": "query",
"_id": "VD7QVmABl04oXt2HGbGB",
"_score": 1.3862944,
"_source": {
"text": "Do you accept credit card ?",
"src": "payment"
}
},
{
"_index": "queries",
"_type": "query",
"_id": "Uj7PVmABl04oXt2HlLFI",
"_score": 0.8630463,
"_source": {
"text": "Take my order",
"src": "place_order"
}
},
{
"_index": "queries",
"_type": "query",
"_id": "UT7PVmABl04oXt2HKLFy",
"_score": 0.6931472,
"_source": {
"text": "I want to order food",
"src": "place_order"
}
}
]
},
"aggregations": {
"src types": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "place_order",
"doc_count": 2,
"best hit": {
"hits": {
"total": 2,
"max_score": 0.8630463,
"hits": [
{
"_index": "queries",
"_type": "query",
"_id": "Uj7PVmABl04oXt2HlLFI",
"_score": 0.8630463,
"_source": {
"text": "Take my order",
"src": "place_order"
}
}
]
}
}
},
{
"key": "payment",
"doc_count": 1,
"best hit": {
"hits": {
"total": 1,
"max_score": 1.3862944,
"hits": [
{
"_index": "queries",
"_type": "query",
"_id": "VD7QVmABl04oXt2HGbGB",
"_score": 1.3862944,
"_source": {
"text": "Do you accept credit card ?",
"src": "payment"
}
}
]
}
}
}
]
}
}
}

希望有帮助!

关于elasticsearch - Elasticsearch:每个关键字的前k个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47774558/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com