如何在Elastic Search中搜索包含不同匹配索引/实体的索引。我需要有复杂的搜索建议,需要按实体进行分组。图像说出千言万语,因此下面的图像描述了我想要实现的内容:
我应该如何建模索引以实现上述目标?
现在我的order
索引如下所示:
{
"_index": "mango",
"_type": "order",
"_id": "4",
"_score": 1,
"_source": {
"number": "000000004",
"customer": {
"id": 14,
"firstName": "Jean",
"lastName": "Hermann",
"email": "lucinda90@example.com"
}
}
}
当我使用文字example.com
进行搜索时,我需要一个回复,看起来有点像(让hits
更加可读):
{
"hits": {
"hits": []
}
"aggregations": {
"customers": [
{
"id": 1,
"firstName": "Mille",
"lastName": "VonRueden",
"email": "shickle@example.com"
},
{
"id": 2,
"firstName": "Clint",
"lastName": "Effertz",
"email": "briana91@example.com"
}
]
}
}
我的搜索查询如何实现此类响应?
我尝试使用以下搜索查询,但它只返回一个空桶:
{
"size": 1,
"aggs": {
"customers": {
"nested": {
"path": "customer"
},
"aggs": {
"name": {
"terms": {
"field": "customer.id"
}
}
}
}
}
}
这是我的订单索引的映射(采用YAML格式):
order:
mappings:
number: ~
createdAt:
type: date
customer:
type: nested
properties:
id :
type : integer
index: not_analyzed
firstName:
type: string
index: not_analyzed
答案 0 :(得分:0)
最简单的方法是为每个实体提供一个索引和映射类型。您显示的屏幕截图可以建模如下:
companies
和映射类型company
groups
和映射类型group
features
和映射类型feature
skills
和映射类型skill
以下是一些示例命令,您可以使用这些命令为每个实体创建索引和映射类型:
curl -XPUT localhost:9200/companies -d '{
"mappings": {
"company": { "properties": { ... }}
}
}'
curl -XPUT localhost:9200/groups -d '{
"mappings": {
"group": { "properties": { ... }}
}
}'
curl -XPUT localhost:9200/features -d '{
"mappings": {
"feature": { "properties": { ... }}
}
}'
curl -XPUT localhost:9200/skills -d '{
"mappings": {
"skill": { "properties": { ... }}
}
}'
然后在搜索时,您需要搜索所有索引和映射类型,并按_type
(asc)和_score
(desc)排序结果:
curl -XPOST 'localhost:9200/_search?q=blog' -d '{
"sort":[
{"_type":"asc"},
{"_score":"desc"}
]
}'
最后,您只需阅读已排序的结果并根据其类型显示它们。
<强>更新强>
跟进您的评论,如果您希望通过汇总进行操作,那么您需要添加top_hits
sub-aggregation:
{
"size": 1,
"aggs": {
"customers": {
"nested": {
"path": "customer"
},
"aggs": {
"name": {
"terms": {
"field": "customer.id"
},
"aggs": { <--- add this
"hits": {
"top_hits: {}
}
}
}
}
}
}
}