Skip to content

Elasticsearch Nested datatype

关于 Nested datatype 的官方介绍: https://www.elastic.co/guide/en/elasticsearch/reference/master/nested.html


简言之:将数组字段的 type 设置为 nested,将会使数组中的每个元素作为单独的文档保存。查询时,数组中的每个元素作为一个整体来匹配查询条件。


查询方法

必须使用 nested 查询,见下例:

json
GET /my_index/blogpost/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "title": "eggs"
                    }
                },
                {
                    "nested": {
                        "path": "comments",
                        "query": {
                            "bool": {
                                "must": [
                                    {
                                        "match": {
                                            "comments.name": "john"
                                        }
                                    },
                                    {
                                        "match": {
                                            "comments.age": 28
                                        }
                                    }
                                ]
                            }
                        }
                    }
                }
            ]
        }
    }
}

使用 Java API 查询

java
QueryBuilder qb = nestedQuery(
	"obj1",                       
	boolQuery()                   
		.must(matchQuery("obj1.name", "blue"))
		.must(rangeQuery("obj1.count").gt(5)),
	ScoreMode.Avg                 
);

  1. Elasticsearch 嵌套式对象 Nested 分析
  2. Elasticsearch 之 Nested(嵌套) 系列