elasticsearch笔记——嵌套查询

      elasticsearch 为了实现水平规模扩展,提供了以下两种形式的查询:

一、nested

      文档中可能包含嵌套类型的字段,这些字段用来索引一些数组对象,每个对象都可以作为一条独立的文档被查询出来。

{
    "mappings": {
        "<type>": {
            "properties": {
                "user": {"type": "nested"}
            }
        }
    }
}
插入的数据:
{
    "user": [
        {
            "first": "John",
            "last": "Smith"
        },
        {
            "first": "Alice",
            "last": "White"
        }
    ]
}
如果字段user的类型采用object,那么添加的数据会扁平化,数据结构会变为:
{
    "user.first": ["John", "Alice"],
    "user.last": ["Smith", "White"]
}
使用以下搜索,上面两条文档就都会被搜索到,而这不是我们想要的:
{
    "query": {
        "bool": {
            "must": {
                "match": {"user.first": "John"},
                "match": {"user.last": "Smith"}
            }
        }
    }
}
如果采用nested类型,会保持数组中每个对象的独立性,使用上面的搜索,只会搜索到一条文档。

二、has_child  和   has_parent 

      has_child:通过子文档查询父文档;

      has_parent:通过父文档查询子文档。

      为了很好的表达清楚,我们构建以下模型:

employee 是 child type;branch 是 parent type。
{
	"mappings": {
		"branch": {
			"properties": {
				"name": {"type": "text"},
				"city": {"type": "text"},
				"country": {"type": "text"}
			}
		},
		"employee": {
			"_parent": {"type": "branch"},
			"properties": {
				"name": {"type": "text"},
				"dob": {"type": "text"},
				"hobby": {"type": "text"}
			}
		}
	}
}

给 branch 插入数据:
{ "index" : { "_id": "london" }}
{ "name" : "London Westminster", "city" : "London", "country" : "UK" }
{ "index" : { "_id": "liverpool" }}
{ "name" : "Liverpool Central", "city" : "liverpool", "country" : "UK" }
{ "index" : { "_id": "paris" }}
{ "name" : "Champs Elysees", "city" : "Paris", "country" : "France" }

给 employee 插入数据:
{ "index" : { "_id" :1, "parent" : "london" }}
{ "name" : "Alice Smith", "dob" : "1970-10-24", "hobby" : "hiking"}
{ "index" : { "_id" :2, "parent" : "london" }}
{ "name" : "Mark Thomas", "dob" : "1982-05-16", "hobby" : "diving"}
{ "index" : { "_id" :3, "parent" : "liverpool" }}
{ "name" : "Barry Smith", "dob" : "1970-04-05", "hobby" : "hiking"}
{ "index" : { "_id" :4, "parent" : "liverpool" }}
{ "name" : "Adrien Grand", "dob" : "1987-10-24", "hobby" : "horses"}

查询1980年以后出生的员工在哪些分支机构(通过查询子文档关联查询父文档):
post localhost:9200/company/branch/_search
{
	"query": {
		"has_child": {
			"type": "employee",
			"query": {
				"range": {
					"dob": {"gte": "1980-01-01"}
				}
			}
		}
	}
}

查询分支机构UK有哪些员工(通过父文档查询子文档):
post localhost:9200/company/employee/_search
{
	"query": {
		"has_parent": {
			"type": "branch",
			"query": {
				"match": {
					"country": "UK"
				}
			}
		}
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值