赞
踩
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"
- }
- }
- }
- }
- }
-
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。