ES中设计一个索引结构包含: name名称、age年龄、sex性别、desc描述。等字段, 使用JAVA API插入多个内容。要求查询出年里在18-35之间,并且姓名包含“李”的所有数据
时间: 2024-02-11 19:05:10 浏览: 151
可以按照以下步骤实现:
1. 创建一个索引,包含name、age、sex、desc等字段,例如:
```
CreateIndexRequest request = new CreateIndexRequest("my_index");
request.settings(Settings.builder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
);
XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties")
.startObject("name")
.field("type", "text")
.endObject()
.startObject("age")
.field("type", "integer")
.endObject()
.startObject("sex")
.field("type", "text")
.endObject()
.startObject("desc")
.field("type", "text")
.endObject()
.endObject()
.endObject();
request.mapping(mappingBuilder);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
```
2. 插入多个文档,例如:
```
List<IndexRequest> requests = new ArrayList<>();
requests.add(new IndexRequest("my_index").source("name", "李明", "age", 20, "sex", "男", "desc", "这是一个描述"));
requests.add(new IndexRequest("my_index").source("name", "张三", "age", 25, "sex", "女", "desc", "这是另一个描述"));
requests.add(new IndexRequest("my_index").source("name", "李四", "age", 30, "sex", "男", "desc", "这是第三个描述"));
BulkRequest bulkRequest = new BulkRequest();
for (IndexRequest request : requests) {
bulkRequest.add(request);
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
```
3. 查询年龄在18-35之间,姓名包含"李"的所有文档,例如:
```
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.rangeQuery("age").gte(18).lte(35))
.must(QueryBuilders.matchQuery("name", "李"));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("my_index")
.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
```
以上是使用Java API实现的示例,其中`client`是一个`RestHighLevelClient`实例,需要根据实际情况进行创建。
阅读全文