小编使用的是elasticsearch-7.3.2
基础说明:
启动:进入elasticsearch-7.3.2/bin目录,双击elasticsearch.bat进行启动,当出现一下界面说明,启动成功。也可以访问http://localhost:9200/
启动ES管理:进入elasticsearch-head-master文件夹,然后进入cmd命令界面,输入npm run start 即可启动。访问http://localhost:9100/ 启动成功。
下面是springboot使用ES的准备工作:
导入相关依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.2</version>
</dependency>
<dependency>
<groupId>com.sksamuel.elastic4s</groupId>
<artifactId>elastic4s_2.11</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.配置ES,创建配置类:CommonConfig
@Configuration
public class CommonConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(
RestClient.builder(
//若有多个,可以传一个数组
new HttpHost("127.0.0.1", 9200, "http")));
}
}
到此,springboot需要使用ES的配置就基本完成了,下面让我们开始进行Java 对ES 的基本操作和以及复杂操作吧。
基础操作:
创建ES索引:(创建表)
@Service
@Slf4j
public class TestService {
@Autowired
public RestHighLevelClient client;
public String createESindex() throws IOException {
//1、构建 创建索引的请求
CreateIndexRequest request = new CreateIndexRequest("base_data");//索引名
//2、客户端执行请求,获取响应
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
//3、打印
System.out.println("创建成功,创建的索引名为:" + response.index());
return "success";
}
}
获取索引,判断索引是否存在:(判断表是否存在)
public String getESindex() throws IOException {
//1、构建 获取索引的请求
GetIndexRequest request = new GetIndexRequest("base_data");
//2、客户端判断该索引是否存在
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
//3、打印
System.out.println("该索引是否存在:"+exists);
return "success";
}
删除索引:(删除表)
public String deleteESindex() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("base_data");
AcknowledgedResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println("删除索引==>"+deleteIndexResponse.isAcknowledged());
return “success”;
}
创建文档:(创建表并插入一条数据)
public String createESdata() throws IOException {
Map<String,Object> base_data=new HashMap<>();
base_data.put("id","a1234");
base_data.put("title","张三");
base_data.put("gender","男");
base_data.put("age","23");
base_data.put("sort_int",1);
base_data.put("time_date","2023-02-25 13:55:23");
base_data.put("is_delete","0");
//1、构建请求
IndexRequest request = new IndexRequest("base_data");
//2、设置规则 PUT /user_index/user/_doc/1
request.id(base_data.get("id")+"");//设置id
request.timeout(TimeValue.timeValueSeconds(1));//设置超时时间
//3、将数据放入到请求中,以JSON的格式存放
request.source(JSONObject.toJSONString(base_data), XContentType.JSON);
//4、客户端发送请求,获取响应结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//5、打印
System.out.println("响应结果:"+response.toString());
return "success";
}
获取文档:(查询表的数据)
public String getESdata() throws IOException {
//获取id为1的文档的信息
GetRequest request = new GetRequest("base_data","a1234");
boolean exists = client.exists(request, RequestOptions.DEFAULT);
System.out.println("文档是否存在:"+exists);
//如果存在,获取文档信息
if (exists){
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println("文档内容为:"+response.getSourceAsString());
}
return "success";
}
修改文档:(修改表中的一条数据)
public String updateESdata() throws IOException {
//更新id为1的文档的信息
UpdateRequest request = new UpdateRequest("base_data", "a1234");
Map<String,Object> setdata=new HashMap<>();
setdata.put("title","铠甲");
request.doc(JSONObject.toJSONString(setdata), XContentType.JSON);
//客户端执行更新请求
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println("更新状态:" +response.status());
return "success";
}
删除一条文档:(删除表中的一条数据)
public String deleteESdata() throws IOException {
//构建删除请求
DeleteRequest request = new DeleteRequest("base_data", "a1234");
//客户端执行删除请求,并获取响应结果
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
//打印
System.out.println("删除状态:"+response.status());
return "success";
}
批量创建数据:(创建表并插入数据)
public String batchinsESdata() throws IOException {
//构建批量插入的请求
BulkRequest request = new BulkRequest();
//设置超时时间
request.timeout("10s");
//构建测试数据
List<Map<String,Object>> data=new ArrayList<>();
Map<String,Object> datamap=null;
for (int i = 0; i < 20; i++) {
datamap=new HashMap<>();
if(i<5){
datamap.put("id","a123b"+i);
datamap.put("title","财务"+i);
datamap.put("user","王刚"+i);
datamap.put("sort_int",6);
datamap.put("is_delete","0");
datamap.put("time_date",StringTimeUtil.now());
}else if(i>5&&i<10){
datamap.put("id","a456b"+i);
datamap.put("title","能源"+i);
datamap.put("user","洪河"+i);
datamap.put("sort_int",i+1);
datamap.put("is_delete","0");
datamap.put("time_date","2023-02-28 12:33:55");
}else if(i>10&&i<15){
datamap.put("id","a789b"+i);
datamap.put("title","光度"+i);
datamap.put("user","时光"+i);
datamap.put("sort_int",i+1);
datamap.put("is_delete","0");
datamap.put("time_date","2023-02-27 12:33:55");
}else{
datamap.put("id","c123d"+i);
datamap.put("title","铠甲"+i);
datamap.put("user","迪迦"+i);
datamap.put("sort_int",i+1);
datamap.put("is_delete","0");
datamap.put("time_date","2023-02-25 12:33:55");
}
data.add(datamap);
}
//批量插入请求设置
for (int i = 0; i < data.size(); i++) {
request.add( new IndexRequest("base_data")//设置索引
.id(data.get(i).get("id")+"")//设置文档的id,如果没有指定,会随机生成,自己测试
.source(JSONObject.toJSONString(data.get(i)), XContentType.JSON)//设置要添加的资源,类型为JSON
);
}
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println("批量插入是否失败:"+response.hasFailures());
return "success";
}
精确查询:(根据ID查询表中的一条数据)
public String queryESdata() throws IOException {
//1、构建搜索请求
SearchRequest request = new SearchRequest("base_data");
//2、设置搜索条件,使用该构建器进行查询
SearchSourceBuilder builder = new SearchSourceBuilder();//生成构建器
//构建精确匹配查询条件
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("_id.keyword", "c123d10");
builder.query(termQueryBuilder);
//3、将搜索条件放入搜索请求中
request.source(builder);
//4、客户端执行搜索请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//5、打印测试
SearchHit[] hits = response.getHits().getHits();
System.out.println("共查询到"+hits.length+"条数据");
System.out.println("查询结果:");
for (int i = 0; i < hits.length; i++) {
System.out.println(hits[i].getSourceAsString());
}
return "success";
}
复杂操作:
1.分页排序查询:(表查询的 limit order by)
public String paginggetESdata() throws IOException {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.from(1);
searchSourceBuilder.size(8);
searchSourceBuilder.trackTotalHits(true);
searchSourceBuilder.sort(SortBuilders.fieldSort("sort_int").order(SortOrder.DESC));//降序
//searchSourceBuilder.sort(SortBuilders.fieldSort("sort_int").order(SortOrder.ASC));//升序
SearchRequest searchRequest = new SearchRequest("base_data");
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = search.getHits().getHits();
System.out.println("ES分页查询返回数据条数==>"+hits.length);
for(SearchHit hit: hits){
JSONObject data_json = JSONObject.parseObject(hit.getSourceAsString());
System.out.println(data_json);
}
return "success";
}
2.按条件查询某些字段:(表查询的select xxx,xxx,xxx from xxx where xxx='xxx' and xxx like '%xxx%')
public String getfieldESdata() throws IOException {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
QueryBuilder dim_q = QueryBuilders.wildcardQuery("title.keyword", "*财务*");//模糊查询
QueryBuilder qeual_q = QueryBuilders.matchPhraseQuery("id", "a123b3");//等量查询
RangeQueryBuilder rang_q=QueryBuilders.rangeQuery("time_date.keyword").from("2023-03-06 15:00:32").to("2023-03-06 19:05:32");//日期区间查询
searchSourceBuilder.query(QueryBuilders.boolQuery().must(dim_q).must(qeual_q).must(rang_q));
//查询指定字段
String[] includeFields = new String[]{"id","title","time_date"};
String[] excludeFields = new String[] {""};
searchSourceBuilder.fetchSource(includeFields, excludeFields);
SearchRequest searchRequest = new SearchRequest("base_data");
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = search.getHits().getHits();
System.out.println("ES复杂查询返回数据条数==>"+hits.length);
for(SearchHit hit: hits){
JSONObject data_json = JSONObject.parseObject(hit.getSourceAsString());
System.out.println(data_json);
}
return "success";
}
3.按条件修改某些字段的值:(表修改的update xxx set xxx='xxx',xxx='xxx' where xxx='xxx' and xxx='xxx')
public String updatebyqueryESdata() throws IOException {
UpdateByQueryRequest request = new UpdateByQueryRequest("base_data");
QueryBuilder upd_q1 = QueryBuilders.matchPhraseQuery("is_delete", "0");//等量条件
QueryBuilder upd_q2 = QueryBuilders.wildcardQuery("title.keyword", "*财务*");//模糊条件
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(upd_q1).must(upd_q2);
String setdata="ctx._source['user']='修改的user';ctx._source['sort_int']=100;ctx._source['title']='修改的title';";
request.setQuery(queryBuilder);
request.setScript(new Script(setdata));
BulkByScrollResponse response = client.updateByQuery(request, RequestOptions.DEFAULT);
System.out.println("受影响行数==>"+response.getStatus().getUpdated());
return "";
}
4.按条件删除文档里面的数据:(表删除的delete from xxx where xxx='xxx' and xxx='xxx')文章来源:https://www.toymoban.com/news/detail-756590.html
public String deletebyqueryESdata() throws IOException {
DeleteByQueryRequest request = new DeleteByQueryRequest("base_data");
QueryBuilder upd_q1 = QueryBuilders.matchPhraseQuery("is_delete", "0");//等量条件
QueryBuilder upd_q2 = QueryBuilders.wildcardQuery("title.keyword", "*修改的*");//模糊条件
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(upd_q1).must(upd_q2);
request.setQuery(queryBuilder);
BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);
System.out.println("受影响行数==>"+response.getStatus().getUpdated());
return "success";
}
以上就是小编自学并根据网络整理的,Java Springboot 操作ES的一些常用业务。整理不易,请大家多多支持,如有不足之处,欢迎大家留言讨论。文章来源地址https://www.toymoban.com/news/detail-756590.html
到了这里,关于Java SpringBoot API 实现ES(Elasticsearch)搜索引擎的一系列操作(超详细)(模拟数据库操作)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!