如何使用Elasticsearch Java Client 8在索引中创建Nested字段
在Java中通过ElasticsearchClient指定POJO字段为nested类型的方法
方法一:使用注解快速配置(适用于Spring Data Elasticsearch场景)
如果你的项目基于Spring Data Elasticsearch,直接在POJO的目标字段上添加@Field(type = FieldType.Nested)注解即可,该字段需定义为对象或对象集合类型。
示例代码:
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; // 父实体类 public class ParentEntity { private String id; // 标记为nested类型的子对象集合 @Field(type = FieldType.Nested) private List<ChildEntity> children; // getter、setter 省略 } // 子实体类 public class ChildEntity { private String name; private int age; // getter、setter 省略 }
当Spring Data Elasticsearch自动创建索引时,会自动将children字段映射为Elasticsearch的nested类型。
方法二:手动构建Mapping(适用于官方Elasticsearch Java Client场景)
如果使用Elasticsearch官方Java Client(8.x及以上版本),可以手动创建索引并指定字段类型为nested,完全控制Mapping结构。
示例代码:
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest; import co.elastic.clients.elasticsearch.indices.CreateIndexResponse; import co.elastic.clients.transport.endpoints.BooleanResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class IndexManager { private final ElasticsearchClient esClient; public IndexManager(ElasticsearchClient esClient) { this.esClient = esClient; } public void createIndexWithNestedField() throws IOException { // 先判断索引是否已存在 BooleanResponse indexExists = esClient.indices().exists(req -> req.index("parent_index")); if (indexExists.value()) { return; } // 构建Mapping结构 Map<String, Object> mapping = new HashMap<>(); Map<String, Object> properties = new HashMap<>(); // 配置普通字段 Map<String, Object> idField = new HashMap<>(); idField.put("type", "keyword"); properties.put("id", idField); // 配置nested字段 Map<String, Object> childrenField = new HashMap<>(); childrenField.put("type", "nested"); Map<String, Object> childProperties = new HashMap<>(); Map<String, Object> nameField = new HashMap<>(); nameField.put("type", "text"); childProperties.put("name", nameField); Map<String, Object> ageField = new HashMap<>(); ageField.put("type", "integer"); childProperties.put("age", ageField); childrenField.put("properties", childProperties); properties.put("children", childrenField); mapping.put("properties", properties); // 发起创建索引请求 CreateIndexRequest createReq = CreateIndexRequest.of(req -> req .index("parent_index") .mappings(mapping) ); CreateIndexResponse response = esClient.indices().create(createReq); System.out.println("索引创建状态:" + response.acknowledged()); } }
注意事项
- 被标记为
nested的字段,Java类型必须是对象或对象集合,不能是基本类型或字符串等简单类型。 - Elasticsearch索引创建后,字段类型无法直接修改,若需调整类型,需重新创建索引并迁移数据。
内容的提问来源于stack exchange,提问作者James Work account
相关产品推荐
相关产品推荐

