一、Maven依赖
在使用Java连接Elasticsearch前,需要在Maven中引入相关的依赖包。在pom.xml文件中添加以下依赖:
<!--elasticsearch客户端-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.14.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.14.0</version>
</dependency>
二、Elasticsearch的连接
在Java中连接Elasticsearch需要使用Elasticsearch的客户端进行连接。可以使用RestHighLevelClient作为HttpClient的包装类,来连接Elasticsearch。在代码中,可以使用以下方法进行连接:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
请注意,代码中的“localhost”为Elasticsearch服务器的地址,“9200”为Elasticsearch服务器的端口号,“http”表示使用的通讯协议为HTTP。
三、Index的增删查改
在Elasticsearch中,索引是一类具有共同属性的文档集合。在Java中可以使用以下方法进行索引的增删查改操作:
1. 创建索引
CreateIndexRequest request = new CreateIndexRequest("your_index_name");
client.indices().create(request, RequestOptions.DEFAULT);
2. 删除索引
DeleteIndexRequest deleteRequest = new DeleteIndexRequest("your_index_name");
client.indices().delete(deleteRequest, RequestOptions.DEFAULT);
3. 判断索引是否存在
IndicesExistsRequest existsRequest = new IndicesExistsRequest("your_index_name");
boolean exists = client.indices().exists(existsRequest, RequestOptions.DEFAULT);
4. 索引配置更新
PutSettingsRequest settingsRequest = new PutSettingsRequest().settings(Settings.builder().put("index.number_of_replicas", 2));
client.indices().putSettings(settingsRequest, RequestOptions.DEFAULT);
5. 索引别名设置
Aliases aliases = new Aliases.Builder().addAlias("alias_name", "index_name").build();
IndicesAliasesRequest aliasesRequest = new IndicesAliasesRequest().addAliasAction(aliases);
client.indices().updateAliases(aliasesRequest, RequestOptions.DEFAULT);
四、 数据的增删查改
在Elasticsearch中,每条记录都称为一个文档。可以使用以下代码进行数据的增删查改等操作:
1. 新增或更新数据
IndexRequest request = new IndexRequest("your_index_name").id("1").source("field_name", "field_value");
client.index(request, RequestOptions.DEFAULT);
2. 删除数据
DeleteRequest deleteRequest = new DeleteRequest("your_index_name").id("1");
client.delete(deleteRequest, RequestOptions.DEFAULT);
3. 判断数据是否存在
GetRequest existsRequest = new GetRequest("your_index_name").id("1");
boolean exists = client.exists(existsRequest, RequestOptions.DEFAULT);
4. 获取数据
GetRequest getRequest = new GetRequest("your_index_name").id("1");
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
String index = response.getIndex();
String id = response.getId();
if (response.isExists()) {
String sourceAsString = response.getSourceAsString();
}
5. 更新数据
UpdateRequest updateRequest = new UpdateRequest("your_index_name", "1").doc("field_name", "field_value");
client.update(updateRequest, RequestOptions.DEFAULT);
五、 数据的批量操作
在实际的应用场景中,可能会需要进行数据的批量操作。以下是几个常用的批量操作方法:
1. 批量新增'
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new IndexRequest("your_index_name").id("1").source("field_name", "field_value"));
bulkRequest.add(new IndexRequest("your_index_name").id("2").source("field_name", "field_value2"));
client.bulk(bulkRequest, RequestOptions.DEFAULT);
2. 全部查询
SearchRequest searchRequest = new SearchRequest("your_index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
3. 条件查询
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.termQuery("field_name", "field_value");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
4. 分页查询
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(0);
sourceBuilder.size(20);
sourceBuilder.query(QueryBuilders.matchAllQuery());
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
5. 范围查询
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.rangeQuery("date_field").gte("2021-01-01").lte("2021-01-31");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
6. 最大值查询
SearchRequest searchRequest = new SearchRequest("your_index_name");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.max("agg_max").field("field_name");
sourceBuilder.aggregation(aggregationBuilder);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
7. 模糊查询
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("field_name", "*test*");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
8.聚合查询
假设有一个包含学生信息的ES索引,每个文档包含了学生的姓名(name)、性别(gender)、年龄(age)和成绩(score)等属性。现在需要对学生数据进行一些聚合统计操作,例如按性别分组计算平均年龄和平均成绩以及每个年龄段中的最高成绩。
//创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//按性别分组计算平均年龄和平均成绩
SearchRequest searchRequest = new SearchRequest("students");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.size(0);
searchSourceBuilder.aggregation(
AggregationBuilders.terms("gender_terms").field("gender")
.subAggregation(AggregationBuilders.avg("age_avg").field("age"))
.subAggregation(AggregationBuilders.avg("score_avg").field("score"))
);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Terms genderTerms = searchResponse.getAggregations().get("gender_terms");
List<? extends Terms.Bucket> buckets = genderTerms.getBuckets();
for (Terms.Bucket bucket : buckets) {
String gender = bucket.getKeyAsString();
Avg ageAvg = bucket.getAggregations().get("age_avg");
double avgAge = ageAvg.getValue();
Avg scoreAvg = bucket.getAggregations().get("score_avg");
double avgScore = scoreAvg.getValue();
System.out.println("Gender: " + gender + ", Avg Age: " + avgAge + ", Avg Score: " + avgScore);
}
//每个年龄段中计算最高成绩
searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.size(0);
searchSourceBuilder.aggregation(
AggregationBuilders.range("age_range").field("age")
.addUnboundedTo(18)
.addRange(18, 20)
.addRange(20, 22)
.addUnboundedFrom(22)
.subAggregation(AggregationBuilders.max("score_max").field("score"))
);
searchRequest.source(searchSourceBuilder);
searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Range ageRange = searchResponse.getAggregations().get("age_range");
for (Range.Bucket bucket : ageRange.getBuckets()) {
String age = bucket.getKeyAsString();
Max scoreMax = bucket.getAggregations().get("score_max");
double maxScore = scoreMax.getValue();
System.out.println("Age: " + age + ", Max Score: " + maxScore);
}
代码中按性别分组计算平均年龄和平均成绩,然后再对每个年龄段中计算最高成绩。聚合查询操作使用“AggregationBuilders”类中的方法来构建聚合查询条件。
9.组合查询
假设有一个包含商品信息的ES索引,每个文档包含了商品的名称(name)、价格(price)、品牌(brand)和类别(category)等属性。现在需要根据用户的查询条件进行组合查询,例如查询价格在一定范围内、品牌为“Samsung”并且类别为“手机”的商品,同时按价格从低到高进行排序。
//创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//组合查询条件
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(
QueryBuilders.boolQuery()
.must(QueryBuilders.rangeQuery("price").gte(1000).lte(2000))
.must(QueryBuilders.termQuery("brand", "Samsung"))
.must(QueryBuilders.termQuery("category", "手机"))
);
searchSourceBuilder.sort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
searchRequest.source(searchSourceBuilder);
//执行查询操作
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
String name = hit.getSourceAsMap().get("name").toString();
String price = hit.getSourceAsMap().get("price").toString();
String brand = hit.getSourceAsMap().get("brand").toString();
String category = hit.getSourceAsMap().get("category").toString();
System.out.println("Product name: " + name + ", Price: " + price + ", Brand: " + brand + ", Category: " + category);
}
代码中使用“QueryBuilders”类中的方法来构建查询条件,查询条件包括价格在一定范围内、品牌为“Samsung”并且类别为“手机”。还使用了“SortBuilders”类中的方法来构建排序条件,按价格从低到高进行排序。
标签:index,name,DEFAULT,searchRequest,client,常用命令,new,ES From: https://blog.51cto.com/learningfish/6318994