Elasticsearchノート-ネストされたクエリー
3662 ワード
Elasticsearchは、水平規模の拡張を実現するために、次の2つの形式のクエリーを提供します.
一、nested
ドキュメントには、配列オブジェクトをインデックスするネストされたタイプのフィールドが含まれます.各オブジェクトは独立したドキュメントとしてクエリーできます.
二、has_childとhas_parent
has_child:サブドキュメントから親ドキュメントをクエリーします.
has_parent:親ドキュメントからサブドキュメントをクエリーします.
明確に表現するために、次のモデルを構築します.
一、nested
ドキュメントには、配列オブジェクトをインデックスするネストされたタイプのフィールドが含まれます.各オブジェクトは独立したドキュメントとしてクエリーできます.
{
"mappings": {
"": {
"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"
}
}
}
}
}