当前位置:   article > 正文

【elastic search】JAVA操作elastic search_java 配置elasticsearch

java 配置elasticsearch

目录

1.环境准备

2.ES JAVA API

3.Spring Boot操作ES


1.环境准备

本文是作者ES系列的第三篇文章,关于ES的核心概念移步:

https://bugman.blog.csdn.net/article/details/135342256?spm=1001.2014.3001.5502

关于ES的下载安装教程以及基本使用,移步:

https://bugman.blog.csdn.net/article/details/135342256?spm=1001.2014.3001.5502

在前文中,我们已经搭建好了一个es+kibana的基础环境,本文将继续使用该环境,演示JAVA操作es。

2.ES JAVA API

Elasticsearch Rest High Level Client 是 Elasticsearch 官方提供的一个 Java 客户端库,用于与 Elasticsearch 进行交互。这个客户端库是基于 REST 风格的 HTTP 协议,与 Elasticsearch 进行通信,提供了更高级别的抽象,使得开发者可以更方便地使用 Java 代码与 Elasticsearch 进行交互。

依赖:

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.17.3</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.3</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.45</version>
</dependency>

其实Rest High Level Client的使用逻辑一共就分散步:

  1. 拼json
  2. 创建request
  3. client执行request

创建client:

RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));

创建索引:

  1. @Test
  2. public void createIndex() throws IOException {
  3. //1.拼json
  4. //settings
  5. Settings.Builder settings = Settings.builder()
  6. .put("number_of_shards", 3)
  7. .put("number_of_replicas", 1);
  8. //mappings
  9. XContentBuilder mappings = JsonXContent.contentBuilder().
  10. startObject().
  11. startObject("properties").
  12. startObject("name").
  13. field("type", "text").
  14. endObject().
  15. startObject("age").
  16. field("type", "integer").
  17. endObject().
  18. endObject().
  19. endObject();
  20. //2.创建request
  21. CreateIndexRequest createIndexRequest = new CreateIndexRequest("person").settings(settings).mapping(mappings);
  22. //3.client执行request
  23. restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
  24. }

创建文档:

  1. @Test
  2. public void createDoc() throws IOException {
  3. Person person=new Person("1","zou",20);
  4. JSONObject json = JSONObject.from(person);
  5. System.out.println(json);
  6. IndexRequest request=new IndexRequest("person",null,person.getId().toString());
  7. request.source(json, XContentType.JSON);
  8. IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
  9. System.out.println(response);
  10. }

响应结果:

修改文档:

  1. @Test
  2. public void updateDoc() throws IOException {
  3. HashMap<String, Object> doc = new HashMap();
  4. doc.put("name","张三");
  5. String docId="1";
  6. UpdateRequest request=new UpdateRequest("person",null,docId);
  7. UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
  8. System.out.println(response.getResult().toString());
  9. }

删除文档:

  1. @Test
  2. public void deleteDoc() throws IOException {
  3. DeleteRequest request=new DeleteRequest("person",null,"1");
  4. DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
  5. System.out.println(response.getResult().toString());
  6. }

响应结果:

搜索示例:

  1. import org.elasticsearch.action.search.SearchRequest;
  2. import org.elasticsearch.action.search.SearchResponse;
  3. import org.elasticsearch.client.RequestOptions;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.elasticsearch.common.unit.TimeValue;
  6. import org.elasticsearch.index.query.QueryBuilders;
  7. import org.elasticsearch.search.builder.SearchSourceBuilder;
  8. import java.io.IOException;
  9. public class ElasticsearchSearchExample {
  10. public static void main(String[] args) {
  11. // 创建 RestHighLevelClient 实例,连接到 Elasticsearch 集群
  12. RestHighLevelClient client = new RestHighLevelClient(
  13. RestClient.builder(new HttpHost("localhost", 9200, "http"))
  14. );
  15. // 构建搜索请求
  16. SearchRequest searchRequest = new SearchRequest("your_index"); // 替换为实际的索引名称
  17. // 构建查询条件
  18. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  19. searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 查询所有文档
  20. // 设置一些可选参数
  21. searchSourceBuilder.from(0); // 设置起始索引,默认为0
  22. searchSourceBuilder.size(10); // 设置返回结果的数量,默认为10
  23. searchSourceBuilder.timeout(new TimeValue(5000)); // 设置超时时间,默认为1分钟
  24. // 将查询条件设置到搜索请求中
  25. searchRequest.source(searchSourceBuilder);
  26. try {
  27. // 执行搜索请求
  28. SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  29. // 处理搜索响应
  30. System.out.println("Search took: " + searchResponse.getTook());
  31. // 获取搜索结果
  32. SearchHits hits = searchResponse.getHits();
  33. System.out.println("Total hits: " + hits.getTotalHits().value);
  34. // 遍历搜索结果
  35. for (SearchHit hit : hits.getHits()) {
  36. System.out.println("Document ID: " + hit.getId());
  37. System.out.println("Source: " + hit.getSourceAsString());
  38. }
  39. } catch (IOException e) {
  40. // 处理异常
  41. e.printStackTrace();
  42. } finally {
  43. try {
  44. // 关闭客户端连接
  45. client.close();
  46. } catch (IOException e) {
  47. // 处理关闭连接异常
  48. e.printStackTrace();
  49. }
  50. }
  51. }
  52. }

请注意,上述示例中的 your_index 应该替换为你实际的 Elasticsearch 索引名称。这个示例使用了简单的 matchAllQuery,你可以根据实际需求构建更复杂的查询条件。在搜索响应中,你可以获取到搜索的结果以及相关的元数据。

3.Spring Boot操作ES

在 Spring Boot 中操作 Elasticsearch 通常使用 Spring Data Elasticsearch,以标准的JPA的模式来操作ES。

依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.x</version> <!-- 选择一个与Elasticsearch 7.17.3兼容的Spring Boot版本 -->
</parent>

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Data Elasticsearch -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

    <!-- Spring Boot Starter Test (for testing) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
application.properties配置:

spring.data.elasticsearch.cluster-nodes=localhost:9200

实体类:

  1. import org.springframework.data.annotation.Id;
  2. import org.springframework.data.elasticsearch.annotations.Document;
  3. import org.springframework.data.elasticsearch.annotations.Field;
  4. import org.springframework.data.elasticsearch.annotations.FieldType;
  5. import java.util.Date;
  6. @Document(indexName = "blogpost_index")
  7. public class BlogPost {
  8. @Id
  9. private String id;
  10. @Field(type = FieldType.Text)
  11. private String title;
  12. @Field(type = FieldType.Text)
  13. private String content;
  14. @Field(type = FieldType.Keyword)
  15. private String author;
  16. @Field(type = FieldType.Date)
  17. private Date publishDate;
  18. // 构造函数、getter和setter
  19. public BlogPost() {
  20. }
  21. public BlogPost(String id, String title, String content, String author, Date publishDate) {
  22. this.id = id;
  23. this.title = title;
  24. this.content = content;
  25. this.author = author;
  26. this.publishDate = publishDate;
  27. }
  28. // 省略 getter 和 setter 方法
  29. }

dao层:

  1. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  2. public interface BlogPostRepository extends ElasticsearchRepository<BlogPost, String> {
  3. // 你可以在这里定义自定义查询方法
  4. }

service层:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.stereotype.Service;
  3. import java.util.List;
  4. import java.util.Optional;
  5. @Service
  6. public class BlogPostService {
  7. private final BlogPostRepository blogPostRepository;
  8. @Autowired
  9. public BlogPostService(BlogPostRepository blogPostRepository) {
  10. this.blogPostRepository = blogPostRepository;
  11. }
  12. public BlogPost save(BlogPost blogPost) {
  13. return blogPostRepository.save(blogPost);
  14. }
  15. public Optional<BlogPost> findById(String id) {
  16. return blogPostRepository.findById(id);
  17. }
  18. public List<BlogPost> findAll() {
  19. return (List<BlogPost>) blogPostRepository.findAll();
  20. }
  21. public void deleteById(String id) {
  22. blogPostRepository.deleteById(id);
  23. }
  24. }


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/477429
推荐阅读
相关标签
  

闽ICP备14008679号