Php Elasticsearch--统计文档中出现的关键字数
数据库:Elasticsearch v7.2Php Elasticsearch--统计文档中出现的关键字数,php,
elasticsearch,Php,
elasticsearch,数据库:Elasticsearch v7.2 应用:Laravel v5.7 使用Elasticsearch/Elasticsearch()官方PHP库 我有一个用于Elasticsearch的查询\u字符串查询,使用此代码可以在我搜索整个索引时检索具有特定短语的文档 [ "query_string" => [ "default_field" => $content, "query" => $keywords ] ], 而$ke
应用:Laravel v5.7
使用Elasticsearch/Elasticsearch()官方PHP库 我有一个用于Elasticsearch的查询\u字符串查询,使用此代码可以在我搜索整个索引时检索具有特定短语的文档
[
"query_string" => [
"default_field" => $content,
"query" => $keywords
]
],
而$keywords
变量包含:
("MCU" OR "Marvel" OR "Spiderman")
现在,我想计算一下我将要检索的文档中这些单词的出现次数
我将aggs查询用于以下内容:
'aggs' => [
'count' => [
'terms' => [
'field' => 'content.keyword'
]
]
]
但是,我不知道如何将这些doc\u count
关联起来,并以匹配的方式显示它与点击数——因为键本身就是内容,而不是ID
Im计划显示整个文档,并与上面提到的每个文档中出现$keywords
的次数有关
是否有其他方法可以不使用Elasticsearch中的
aggs
来计算出现次数?如果您只想计算关键字的出现次数,则不必启用fielddata,请在查询时尝试过滤器aggs
GET my_index/_search
{
"query": {
"query_string": {
"default_field": "content",
"query": "MCU OR Marvel OR Spiderman"
}
},
"aggs": {
"count": {
"filters": {
"filters": {
"mcu": {
"match": {
"content": "MCU"
}
},
"marvel": {
"match": {
"content": "Marvel"
}
},
"spiderman": {
"match": {
"content": "Spiderman"
}
}
}
}
}
}
}
结果如下所示:
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 4,
"max_score": 1.219939,
"hits": [
....
....
]
},
"aggregations": {
"count": {
"buckets": {
"marvel": {
"doc_count": 2
},
"mcu": {
"doc_count": 2
},
"spiderman": {
"doc_count": 1
}
}
}
}
}
来源:启用FieldData可能不是启用文本搜索的最佳方式
在启用FieldDATA之前,请考虑为什么要使用文本字段进行聚合、排序或脚本。这样做通常没有意义
在索引之前分析文本字段,以便通过搜索New或for York找到类似New York的值。当您可能需要一个名为new york的bucket时,此字段上的术语聚合将返回一个新bucket和一个york bucket 相反,您应该有一个用于全文搜索的文本字段,以及一个具有聚合启用的doc_值的未分析关键字字段,如下所示:多亏了@AshrafulIslam爵士,我才想出了Elasticsearch名为
亮点的功能。虽然突出显示了字面上强调了出现的关键字,但我还是求助于PHP的substr\u count()
函数来计算
标记
我将此代码添加为['body']['query']
元素的同级:
"highlight" => [
"fields" => [
"content" => ["number_of_fragments" => 0]
],
'require_field_match' => false
]
然后,当我在['hits']['hits']
数组元素中循环时,我执行了如下操作:
$articles = $client->search($params);
$hits = $articles['hits']['hits'];
for($i=0; $i<count($hits); $i++){
$hits[$i]['_source']['count_mentions'] = substr_count($hits[$i]['highlight']['content'][0],"<em>");
}
$articles=$client->search($params);
$hits=$articles['hits']['hits'];
对于($i=0;$ihello先生,是否有办法统计我的$keywords
在文档中出现的次数(特别是在内容字段中)没有使用aggs
?@JueViole17更新了答案,添加了新的方法来只计算关键字的出现次数ssir@AshrafulIslam感谢您对响应的有用更新,非常感谢!但是,我的$keywords
变量是动态的——在我的PHP应用程序中,每个登录后,将更改$keywords
的内容,因为$keywords
根据登录的用户而定…我是否应该将您的答案更改为:“mcu”:{“匹配”:{“内容”:$keywords}
@JueViole17如果您将关键字放入匹配查询,则它将与总点击数相同。相反,对于每个关键字,请使用格式为“$keyword”:{“match”:{“content”:$keyword}的过滤器查询
您可以使用ElasticSearch突出显示功能突出显示搜索查询的出现次数,然后从PHP端开始计算。
$articles = $client->search($params);
$hits = $articles['hits']['hits'];
for($i=0; $i<count($hits); $i++){
$hits[$i]['_source']['count_mentions'] = substr_count($hits[$i]['highlight']['content'][0],"<em>");
}