一、Nested类型的介绍
Elasticsearch Nested类型是指将一个对象数组作为一个字段进行索引。Nested类型是一种特殊的对象类型,它可以用来存储在嵌套对象中包含的其他对象信息。这个Nested对象可看做是一个嵌套的对象和它的子文档的集合,可以在同一个document中进行索引。
为了使用Nested类型,要使用下面三个步骤:
1、创建一个mapping
2、在该字段上使用Nested类型,并在字段中定义它内部的对象或属性
3、存储和查询数据
{
"mappings": {
"properties": {
"manufacturer": {
"type": "nested",
"properties": {
"name": { "type": "text" },
"location": { "type": "geo_point" }
}
}
}
}
}
二、Nested类型的应用场景
Nested类型主要应用于以下两种情况:
1、嵌套的对象具有多个属性,每个属性都需要各自独立地搜索。
2、嵌套的对象通常会作为一个整体来搜索,比如博客文章,具有标题、正文、标签等属性。
在这些情况下,Nested类型都可以发挥出很好的效果。然而,Nested类型也存在一些缺点。Nested类型会在内存中重复保存与其相关的文档,因此在数据压缩时,内存需求量会增加。
三、Nested类型的使用方式
1、创建Mapping
Nested类型必须在索引mapping时,作为一种复合类型进行定义。
PUT nested_test
{
"mappings": {
"properties": {
"name": {"type": "keyword"},
"age": {"type": "integer"},
"sex": {"type": "keyword"},
"notes": {
"type": "nested",
"properties": {
"title": {"type": "text"},
"content": {"type": "text"},
"date": {"type": "date"}
}
}
}
}
}
2、索引文档
Nested类型字段的支持直接给定内部对象的一个数组,配合它的properties实现保存、查询和表达式计算的支持。
PUT /index/_doc/1
{
"name":"tom",
"age":18,
"sex":"male",
"notes":[
{
"title":"note1",
"content":"hello elasticsearch",
"date":"2020-01-01"
},
{
"title":"note2",
"content":"hello nested type",
"date":"2020-01-02"
}
]
}
3、查询Nested类型
在查询时,Nested类型的字段要进行特殊处理。要查询内部的字段时,必须使用dot notation指明嵌套字段和其属性名称。
GET index/_search
{
"query": {
"nested": {
"path": "notes",
"query": {
"bool": {
"must": [
{"match": {"notes.title": "note1"}},
{"range": {"notes.date": {"gt":"2019-12-31"}}}
]
}
}
}
}
}
四、Nested类型的注意事项
1、嵌套字段不能被映射为子文档或其他同级的Object类型。
2、Nested类型内部如果有多个属性,则每个属性都是一个单独的字段。
3、Nested类型不支持聚合查询。
4、嵌套文档必须具备唯一标识。
5、查询时,必须使用Nested类型的嵌套路径。
6、存储和查询数据的性能延迟比较高。
五、总结
本篇文章通过介绍Nested类型的基本信息、使用方式及注意事项,让读者对Nested类型有了一个更深入的了解。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/190305.html
微信扫一扫
支付宝扫一扫