您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
elasticSearch的has_child查询
发布时间:2021-09-07 17:36:56编辑:雪饮阅读()
ElasticSearch中has_child查询主要是以匹配子文档来返回响应其父文档。
那么既然是父子文档查询,所以我们先建立拥有父子关系的索引。
请求体:
{
"mappings": {
"properties": {
"my_join_field": {
"type": "join",
"relations": {
"parent_article": "article"
}
}
}
}
}
响应体:
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "tutorials"
}
然后索引父文档
请求体:
{
"name":"Parent School1", "Text":"This is article 1 of chapter 1(parent)", "street":"Nagan",
"city":"paprola", "state":"HP", "zip":"176115", "location":[31.8955385, 76.8380405],
"fees":2200, "tags":["Senior Secondary", "beautiful campus"], "rating":"3.3",
"my_join_field": {
"name":"parent_article"
}
}
响应体:
{
"_index": "tutorials",
"_type": "_doc",
"_id": "parent_article_1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
然后索引子文档
请求体:
{
"name":"Parent School1", "Text":"This is article 1 of chapter 1(child)", "street":"Nagan",
"city":"paprola", "state":"HP", "zip":"176115", "location":[31.8955385, 76.8380405],
"fees":2200, "tags":["Senior Secondary", "beautiful campus"], "rating":"3.3",
"my_join_field":{
"name":"article",
"parent":"parent_article_1"
}
}
响应体:
{
"_index": "tutorials",
"_type": "_doc",
"_id": "article1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 3,
"_primary_term": 1
}
然后我们就可以进行has_child查询了
请求体:
{
"query":
{
"has_child" : {
"type" : "article",
"query" : {
"match" : {
"Text" : "This is article 1 of chapter 1(child)"
}
}
}
}
}
响应体:
{
"took": 65,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "tutorials",
"_type": "_doc",
"_id": "parent_article_1",
"_score": 1.0,
"_source": {
"name": "Parent School1",
"Text": "This is article 1 of chapter 1(parent)",
"street": "Nagan",
"city": "paprola",
"state": "HP",
"zip": "176115",
"location": [
31.8955385,
76.8380405
],
"fees": 2200,
"tags": [
"Senior Secondary",
"beautiful campus"
],
"rating": "3.3",
"my_join_field": {
"name": "parent_article"
}
}
}
]
}
}
可以看到我has_child查询中type指定是子文档的相对于父子关系索引中的角色定位。
然后是match到Text字段以”This is article 1 of chapter 1(child)
”进行匹配,但是会发现最后响应结果中的文档的Text的值为”
This is article 1 of chapter 1(parent)
这样正好应了前面所说的has_child查询是查询匹配子文档,然后返回对应的父文档。
关键字词:elasticSearch,has_child,查询