ElasticSearch JAVA API操作
获取示例代码
pom.xml导入依赖
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!--elasticsearch客户端-->
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
创建 User 实体类
package com.zhoujing.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author 周敬
* @version 1.0
* @createTime 2022/4/28-11:51-星期四
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private Character sex;
private Integer age;
}
以下使用 junit 测试类
索引操作
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
/**
* ES索引操作
* @author 周敬
* @version 1.0
* @createTime 2022/4/26-20:29-星期二
*/
public class ESIndexTest {
//===================================== 连接/关闭操作 ===========================================
private RestHighLevelClient esClient;
/**
* 连接ES
* @throws IOException
*/
@Before
public void connectionES() throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
this.esClient = esClient;
}
@After
public void closeES() throws IOException {
//关闭es客户端
esClient.close();
}
//============================================================================================
/**
* 创建索引
*/
@Test
public void createIndex() throws IOException {
//创建索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
//相应状态
final boolean b = response.isAcknowledged();
if(b){
System.out.println("响应创建成功");
}
}
/**
* 查询索引
* @throws IOException
*/
@Test
public void indexSearch() throws IOException {
//创建索引
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println(response.getAliases());
System.out.println(response.getMappings());
System.out.println(response.getSettings());
}
/**
* 删除索引
* @throws IOException
*/
@Test
public void deleteIndex() throws IOException {
//删除索引
DeleteIndexRequest request = new DeleteIndexRequest("user");
//响应结果
AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
final boolean b = response.isAcknowledged();
if(b){
System.out.println("删除索引成功");
}
}
}
文档操作
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhoujing.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
/**
* ES文档操作
* @author 周敬
* @version 1.0
* @createTime 2022/4/28-11:49-星期四
*/
public class ESDocTest {
//===================================== 连接/关闭操作 ===========================================
private RestHighLevelClient esClient;
/**
* 连接ES
* @throws IOException
*/
@Before
public void connectionES() throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
this.esClient = esClient;
}
@After
public void closeES() throws IOException {
//关闭es客户端
esClient.close();
}
//============================================================================================
/**
* 插入数据
* @throws IOException
*/
@Test
public void createDoc() throws IOException {
//插入数据
IndexRequest request = new IndexRequest();
request.index("user").id("1001");
User user = new User("小明",'男',20);
//转JSON
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}
/**
* 查询文档
* @throws IOException
*/
@Test
public void searchDoc() throws IOException {
//获取到文档
GetRequest request = new GetRequest();
request.index("user").id("1001");
GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSource());
}
/**
* 修改文档
* @throws IOException
*/
@Test
public void updateDoc() throws IOException {
//获取到文档
UpdateRequest request = new UpdateRequest();
request.index("user").id("1001");
//将性别修改为女
request.doc(XContentType.JSON,"sex","女");
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}
/**
* 删除文档
* @throws IOException
*/
@Test
public void deleteDoc() throws IOException {
//获取到文档
DeleteRequest request = new DeleteRequest();
request.index("user").id("1001");
DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}
}
文档批量操作
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
/**
* ES文档批量操作
* @author 周敬
* @version 1.0
* @createTime 2022/4/28-13:03-星期四
*/
public class ESDocBulkTest {
//===================================== 连接/关闭操作 ===========================================
private RestHighLevelClient esClient;
/**
* 连接ES
* @throws IOException
*/
@Before
public void connectionES() throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
this.esClient = esClient;
}
@After
public void closeES() throws IOException {
//关闭es客户端
esClient.close();
}
//============================================================================================
/**
* 批量插入
* @throws IOException
*/
@Test
public void bulkAdd() throws IOException {
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON,"name","小红","sex","女","age",18));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","小白","sex","男","age",23));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","小黄","sex","男","age",19));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON,"name","xiaohong","sex","女","age",18));
request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON,"name","xiaobai","sex","男","age",23));
request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON,"name","xiaohuang","sex","男","age",19));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
//每个响应的结果
for (BulkItemResponse item : response.getItems()) {
System.out.println(item.getResponse().getResult());
}
//批量所消耗的时间
System.out.println(response.getTook());
}
/**
* 批量删除
* @throws IOException
*/
@Test
public void bulkDelete() throws IOException {
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1001"));
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
//每个响应的结果
for (BulkItemResponse item : response.getItems()) {
System.out.println(item.getResponse().getResult());
}
//批量所消耗的时间
System.out.println(response.getTook());
}
}
高级搜索
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.adjacency.AdjacencyMatrixAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
/**
* ES文档高级查询
* @author 周敬
* @version 1.0
* @createTime 2022/4/28-13:30-星期四
*/
public class ESDocAdvancedQueryTest {
//===================================== 连接/关闭操作 ===========================================
private RestHighLevelClient esClient;
/**
* 连接ES
* @throws IOException
*/
@Before
public void connectionES() throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
this.esClient = esClient;
}
@After
public void closeES() throws IOException {
//关闭es客户端
esClient.close();
}
//============================================================================================
/**
* 全量查询
* 获取索引中user的所有数据
* @throws IOException
*/
@Test
public void searchAll() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 条件查询
* 查询性别为女的用户
* @throws IOException
*/
@Test
public void conditionQuery() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.termQuery("sex","女"));
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 分页查询
* @throws IOException
*/
@Test
public void pagingQuery() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//from:当前页
//size:每页大小
sourceBuilder.from(0);
sourceBuilder.size(2);
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 排序
* 根据年龄排序
* @throws IOException
*/
@Test
public void orderQuery() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//根据年龄进行升序排序
sourceBuilder.sort("age", SortOrder.ASC);
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 排除属性
* 将年龄属性排除掉
* @throws IOException
*/
@Test
public void excludeAttribute() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//排除的属性
String[] excludes = {"age"};
//包括的属性
String[] includes = {};
sourceBuilder.fetchSource(includes,excludes);
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 组合查询
* @throws IOException
*/
@Test
public void combinationSearch() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//=====================================条件(选择其中一种)==========================================
//年龄为23并且名称为小白的用户
boolQueryBuilder.must(QueryBuilders.matchQuery("age",23));
boolQueryBuilder.must(QueryBuilders.matchQuery("name","小白"));
//年龄为23并且名称不为小白的用户
boolQueryBuilder.must(QueryBuilders.matchQuery("age",23));
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name","小白"));
//年龄为23或者年龄为19的用户
boolQueryBuilder.should(QueryBuilders.matchQuery("age",23));
boolQueryBuilder.should(QueryBuilders.matchQuery("age",19));
//================================================================================================
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 范围查询
* @throws IOException
*/
@Test
public void scopeQuery() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = new RangeQueryBuilder("age");
//=====================================条件(选择其中一种)==========================================
//年龄大于等于20小于等于50
rangeQuery.gte(20);
rangeQuery.lte(50);
//年龄大于20小于50
rangeQuery.gt(20);
rangeQuery.lt(50);
//================================================================================================
builder.query(rangeQuery);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 模糊查询
* @throws IOException
*/
@Test
public void fuzzyQuery() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder builder = new SearchSourceBuilder();
//对name进行模块查询。[注意:中文会导致模糊查询失效]
//Fuzziness:误差范围
//Fuzziness.ZERO:只能容纳零个字符的误差
//Fuzziness.ONE:只能容纳一个字符的误差
//Fuzziness.TWO:只能容纳二个字符的误差
FuzzyQueryBuilder fuzziness = QueryBuilders.fuzzyQuery("name", "xiaohong").fuzziness(Fuzziness.ZERO);
builder.query(fuzziness);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getSourceAsString());
});
}
/**
* 高亮查询
* @throws IOException
*/
@Test
public void highlighSearch() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "xiaohong");
//对查询的结果进行标签的前后置拼接
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");
highlightBuilder.postTags("</font>");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(termQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
System.out.println(his.getHighlightFields());
});
}
/**
* 聚合函数
* @throws IOException
*/
@Test
public void aggregationSearch() throws IOException {
SearchRequest request = new SearchRequest();
//indices可以理解为索引的集合
//index为具体的索引,index需要指定id
request.indices("user");
//查询条件:查询所有
SearchSourceBuilder builder = new SearchSourceBuilder();
//=====================================条件(选择其中一种)==========================================
//查询最大的年龄
AggregationBuilder aggregation1 = AggregationBuilders.max("MaxAge").field("age");
//查询最小的年龄
AggregationBuilder aggregation2 = AggregationBuilders.max("MinAge").field("age");
//对年龄进行分组
AggregationBuilder aggregation3 = AggregationBuilders.max("GroupAge").field("age");
//================================================================================================
builder.aggregation(aggregation1);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("共消耗:"+response.getTook());
//输出所有内容
hits.forEach(his -> {
try {
System.out.println(new ObjectMapper().writeValueAsString(response.getAggregations()));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
});
}
}
|