ES搜索nested类型错误
参考官网:https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html#nested-fields-array-objects
The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.
How arrays of Object are flattened
Elasticsearch has no concept of inner objects. Therefore, it flattens object hierarchies into a simple list of field names and values. For instance, consider the following document:
# 添加索引数据,此时索引类型没有在mapping中指定为nested
PUT my-index-000001/_doc/1
{
"group" : "fans",
"user" : [
{
"first" : "John",
"last" : "Smith"
},
{
"first" : "Alice",
"last" : "White"
}
]
}
# 查询数据
GET my-index-000001/_search
{
"query": {
"bool": {
"must": [
{ "match": { "user.first": "Alice" }},
{ "match": { "user.last": "White" }}
]
}
}
}
如果创建索引没有指定类型,或者先插入数据再创建索引,则会提示:
{
"error": {
"root_cause": [
{
"type": "aggregation_execution_exception",
"reason": "[nested] nested path [user] is not nested"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "my-index-000001",
"node": "abcdefghijk-lmn",
"reason": {
"type": "aggregation_execution_exception",
"reason": "[nested] nested path [user] is not nested"
}
}
]
},
"status": 500
}
因此需要做如下操作:
1.清空数据
2.删除索引
3.重建索引
4.填充数据
5.查询
# 创建索引,指定索引类型中user类型为nested
PUT my-index-000001
{
"mappings": {
"properties": {
"user": {
"type": "nested"
}
}
}
}
# 添加数据到索引
PUT my-index-000001/_doc/1
{
"group" : "fans",
"user" : [
{
"first" : "John",
"last" : "Smith"
},
{
"first" : "Alice",
"last" : "White"
}
]
}
# 查询索引数据
GET my-index-000001/_search
{
"query": {
"nested": {
"path": "user",
"query": {
"bool": {
"must": [
{ "match": { "user.first": "Alice" }},
{ "match": { "user.last": "Smith" }}
]
}
}
}
}
}
# 查询索引数据
GET my-index-000001/_search
{
"query": {
"nested": {
"path": "user",
"query": {
"bool": {
"must": [
{ "match": { "user.first": "Alice" }},
{ "match": { "user.last": "White" }}
]
}
},
"inner_hits": {
"highlight": {
"fields": {
"user.first": {}
}
}
}
}
}
}