赞
踩
1.使用elasticsearch高级客户端api
Java High Level REST Client | Java REST Client [7.15] | Elastic
2.本人用的elasticsearch版本就是7.14,使用api版本是7.15.2 ,使用es版本对应版本或者高一点版本没问题 以免造成不必要麻烦
3.可以边看官网边看这个例子 ,废话不多说,先上依赖上代码
- <!--es 高级客户端 包含org.elasticsearch-->
- <dependency>
- <groupId>org.elasticsearch.client</groupId>
- <artifactId>elasticsearch-rest-high-level-client</artifactId>
- <version>7.15.2</version>
- </dependency>
- <!--es bug导致运行异常,缺少包,优先引入上面的,如果不报错,下面这个不需要引入,-->
- <dependency>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- <version>7.15.2</version>
- </dependency>
其实引入一个
elasticsearch-rest-high-level-client 这个主依赖包含 org.elasticsearch这个依赖,但是本人遇到一个问题,启动项目会报错
Caused by: java.lang.ClassNotFoundException: org.elasticsearch.common.xcontent.DeprecationHandler
导致jar引入不完整导致的,咱们在引入一遍,确保jar的完整
4.解决maven依赖问题,我们就可以搞点测试类玩玩啦
springboot 下面 引入一下测试类吧,或者不用测试类都可以。有的同学项目创建时候不勾选test依赖,可以引入下
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
(2)其实安装个Maven Dependency Helper这个插件不错,帮你找到你设置镜像查到依赖
简直牛B666
,这里不用版本,默认跟boot版本一致。
4.下一步就是配置啦springboot配置一下 连接es的config类,让spring扫描到,直接上代码啦
- package com.example.helloshirodemo.common.es;
-
- import lombok.extern.slf4j.Slf4j;
- import org.apache.http.HttpHost;
- import org.elasticsearch.client.RequestOptions;
- import org.elasticsearch.client.RestClient;
- import org.elasticsearch.client.RestHighLevelClient;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- import java.io.IOException;
-
- /**
- * @author zhang
- * @version 1.0
- * @date 2022/1/19 9:26
- */
- @Configuration
- @Slf4j
- public class ElasticSearchConfig {
-
- public static final RequestOptions COMMON_OPTIONS;
- //hostName 代表ip
- @Value("${elasticsearch.cluster-nodes}")
- private String hostName;
- //因为咱们这个高级客户端rest 是基于http 咱们使用端口9200 ,而9300是tcp
- @Value("${elasticsearch.port}")
- private int port;
- static {
- // RequestOptions类保存了请求的部分,这些部分应该在同一个应用程序中的许多请求之间共享。
- // 创建一个singqleton实例,并在所有请求之间共享它。可以设置请求头之类的一些配置
- RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
- // builder.addHeader("Authorization", "Bearer " + TOKEN); //增加需要的请求 头
- // builder.setHttpAsyncResponseConsumerFactory(
- // new HttpAsyncResponseConsumerFactory
- // .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 *1024));
- COMMON_OPTIONS = builder.build();
- }
- //创建ES实例
- @Bean
- public RestHighLevelClient restHighLevelClient() throws IOException {
-
- RestHighLevelClient client = new RestHighLevelClient(
- RestClient.builder(new HttpHost(
- hostName, port, "http"
- )));
- return client;
- }
- }
9200用于外部通讯,基于http协议,程序与es的通信使用9200端口。
9300jar之间就是通过tcp协议通信,遵循tcp协议,es集群中的节点之间也通过9300端口进行通信。
5.配置完毕,就可以使用啦,操作一下api 吧,创建个测试类
项目结构 要对应
- package com.example.helloshirodemo;
-
- import com.example.helloshirodemo.common.es.ElasticSearchConfig;
- import org.elasticsearch.ElasticsearchException;
- import org.elasticsearch.action.ActionListener;
- import org.elasticsearch.action.DocWriteResponse;
- 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.search.SearchRequest;
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.action.support.AdapterActionFuture;
- import org.elasticsearch.client.Cancellable;
- import org.elasticsearch.client.ElasticsearchClient;
- import org.elasticsearch.client.RestHighLevelClient;
- import org.elasticsearch.client.core.MainResponse;
- import org.elasticsearch.common.unit.Fuzziness;
- import org.elasticsearch.common.xcontent.XContentBuilder;
- import org.elasticsearch.common.xcontent.XContentType;
- import org.elasticsearch.core.TimeValue;
- import org.elasticsearch.index.query.MatchQueryBuilder;
- import org.elasticsearch.index.query.QueryBuilders;
- import org.elasticsearch.search.SearchHit;
- import org.elasticsearch.search.builder.SearchSourceBuilder;
- import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import javax.naming.directory.SearchResult;
- import java.io.IOException;
- import java.net.ConnectException;
- import java.util.Date;
- import java.util.Map;
- import java.util.UUID;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.TimeUnit;
-
- /**
- * @author zhang
- * @version 1.0
- * @date 2022/1/19 10:04
- */
- @SpringBootTest
- public class Test1 {
-
- @Autowired
- private RestHighLevelClient restHighLevelClient;
- /*创建索引 插入文档*/
- @Test
- public void test001() throws IOException {
- IndexRequest indexRequest = new IndexRequest("indexrequest");
- indexRequest.id(UUID.randomUUID().toString().replaceAll("-",""));
- String jsonString = "{" +
- "\"user\":\"kimchy\"," +
- "\"postDate\":\"2013-01-30\"," +
- "\"message\":\"trying out Elasticsearch\"" +
- "}";
- indexRequest.source(jsonString, XContentType.JSON);
- IndexResponse index = restHighLevelClient.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
- DocWriteResponse.Result result = index.getResult();
- if(DocWriteResponse.Result.CREATED.equals(index.getResult())){
- System.out.println("创建索引 插入文档完毕!!");
- }
- }
- /*获取指定索引下的 id 文档*/
- @Test
- public void test002() throws IOException {
- GetRequest getRequest = new GetRequest("indexrequest");
- getRequest.id("0e8e3045e7da4c07a66cf36fb0725835");
- GetResponse documentFields = restHighLevelClient.get(getRequest, ElasticSearchConfig.COMMON_OPTIONS);
- Map<String, Object> source = documentFields.getSource();
- System.out.println(source);
- }
- @Test
- public void test003() throws IOException {
- try {
- if(restHighLevelClient.ping(ElasticSearchConfig.COMMON_OPTIONS)){
- System.out.println("链接成功es");
- }
- }catch (Exception e){
- if(e instanceof ElasticsearchException){
- System.out.println("ConnectException链接失败");
- }
- }
- }
- /*模糊查询*/
- @Test
- public void test004() throws IOException {
- //创建搜索请求。如果没有参数,这将对所有索引运行。
- SearchRequest searchRequest = new SearchRequest("t_blog");
- //大多数搜索参数都添加到SearchSourceBuilder中。它为进入搜索请求主体的所有内容提供了setter。
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", "标题2");
- matchQueryBuilder.fuzziness(Fuzziness.AUTO); //开启模糊性查询
- matchQueryBuilder.prefixLength(3); //模糊前缀
- matchQueryBuilder.maxExpansions(10); //设置最大扩展选项
- // searchSourceBuilder.query(QueryBuilders.matchQuery("text","标题2"));
- searchSourceBuilder.query(matchQueryBuilder);
- searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
- searchRequest.source(searchSourceBuilder);
- SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
- SearchHit[] hits = search.getHits().getHits();
- for (SearchHit hit : hits) {
- System.out.println(hit);
- }
- }
- /*高亮查询*/
- @Test
- public void heihtQueryTest01() throws IOException {
- //指定搜素请求信息
- SearchRequest searchRequest = new SearchRequest("t_blog"); //index
- //创建搜素源生成器
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- //匹配
- MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", "标题2");
- //高亮
- HighlightBuilder highlightBuilder = new HighlightBuilder();
- HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title");
- highlightBuilder.preTags("<span style='color:red' >");//设置前缀
- highlightBuilder.postTags("</span>");//设置后缀
- highlightBuilder.field(highlightTitle);
- //设置高亮
- searchSourceBuilder.highlighter(highlightBuilder);
- //匹配器设置匹配规则
- searchSourceBuilder.query(matchQueryBuilder);
- //设置排序
- searchSourceBuilder.sort("createTime");
- //设置分页
- searchSourceBuilder.from(0); //页吗
- searchSourceBuilder.size(10);//默认命中10
- searchRequest.source(searchSourceBuilder);
-
- SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
- for (SearchHit hit : search.getHits().getHits()) {
- Map<String, Object> sourceAsMap = hit.getSourceAsMap();
- System.out.println(sourceAsMap);
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。