前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot集成ES-7.8

SpringBoot集成ES-7.8

原创
作者头像
BNTang
发布2023-10-01 20:12:49
1970
发布2023-10-01 20:12:49
举报

原生依赖

代码语言:html
复制
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.8.1</version>
</dependency>

初始化对象

代码语言:java
复制
RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));
代码语言:java
复制
client.close();

然后分析这个对象中的方法即可(api)

创建项目

这里以https://start.spring.io/的方式进行创建

?环境规定

  • SpringBoot:2.2.5.RELEASE
  • JDK:1.8

?修改elasticsearch.version

代码语言:html
复制
<properties>
	<elasticsearch.version>7.8.1</elasticsearch.version>
</properties>

?创建配置类ElasticSearchClientConfig.java

代码语言:java
复制
@Configuration
public class ElasticSearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
    }

}

索引API

创建索引

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testCreateIndex() throws IOException {
        // 1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("bntang666_index");

        // 2.客户端执行请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(response);
    }

}

判断索引是否存在

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testExistsIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("bntang666_index");

        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

        System.out.println(exists);
    }

}

删除索引

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("test2");

        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

        System.out.println(response.isAcknowledged());
    }
}

文档API

创建POJO(实体类)

代码语言:java
复制
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private String name;
    private int age;
}

添加文档

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testAddDocument() throws IOException {
        // 1.创建对象
        User user = new User("灰灰", 23);

        // 2.创建请求
        IndexRequest request = new IndexRequest("bntang666_index");

        // 3.规则
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));

        // 4.将我们的数据放入请求中
        request.source(JSON.toJSONString(user), XContentType.JSON);

        // 5.客户端发送请求,获取响应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
        System.out.println(response.status());
    }

}

判断文档是否存在

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testIsExists() throws IOException {
        GetRequest request = new GetRequest("bntang666_index","1");

        // 不获取返回的_source的上下文了
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");

        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

}

获取文档信息

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testGetDocument() throws IOException {
        GetRequest request = new GetRequest("bntang666_index", "1");

        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSource());
        System.out.println(response);
    }

}

修改文档信息

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("bntang666_index", "1");
        request.timeout("1s");

        User user = new User("灰灰说Java", 18);

        request.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

}

删除文档信息

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("bntang666_index", "1");
        request.timeout("1s");

        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

}

批量插入文档信息

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testBatchInsertDocument() throws IOException {
        BulkRequest request = new BulkRequest();
        request.timeout("10s");

        List<Object> list = new ArrayList<>();
        list.add(new User("BNTang1", 23));
        list.add(new User("BNTang2", 23));
        list.add(new User("BNTang3", 23));

        list.add(new User("BNTang6661", 23));
        list.add(new User("BNTang6662", 23));
        list.add(new User("BNTang6663", 23));

        for (int i = 0; i < list.size(); i++) {
            request.add(
                    new IndexRequest("bntang666_index")
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
        }

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.hasFailures());
    }

}

?批量修改和批量删除只需要在循环当中修改对应的API即可

查询API

精确查询

代码语言:java
复制
@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void testSearch() throws IOException {
        SearchRequest request = new SearchRequest("bntang666_index");

        // 构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 查询条件,我们可以使用
        TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "BNTang1");
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response.getHits()));
        System.out.println("======================================");

        for (SearchHit searchHit : response.getHits().getHits()) {
            System.out.println(searchHit.getSourceAsMap());
        }
    }

}
  • SearchRequest:搜索请求
  • SearchSourceBuilder:条件构造
  • HighlightBuilder:构建高亮
  • TermQueryBuilder:精确查询
  • MatchAllQueryBuilder:匹配所有

xxx QueryBuild 对应的就是Kibana中的命令

我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 原生依赖
  • 初始化对象
  • 创建项目
  • 索引API
    • 创建索引
      • 判断索引是否存在
        • 删除索引
        • 文档API
          • 添加文档
            • 判断文档是否存在
              • 获取文档信息
                • 修改文档信息
                  • 删除文档信息
                    • 批量插入文档信息
                    • 查询API
                      • 精确查询
                      相关产品与服务
                      Elasticsearch Service
                      腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
                      http://www.vxiaotou.com