【elastic search】JAVA操作elastic search

这篇具有很好参考价值的文章主要介绍了【elastic search】JAVA操作elastic search。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

【elastic search】JAVA操作elastic search,elastic search,JAVA EE,java,elasticsearch

【elastic search】JAVA操作elastic search,elastic search,JAVA EE,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")));

创建索引:

@Test
    public void createIndex() throws IOException {
        //1.拼json
        //settings
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 3)
                .put("number_of_replicas", 1);
        //mappings
        XContentBuilder mappings = JsonXContent.contentBuilder().
                startObject().
                    startObject("properties").
                    startObject("name").
                        field("type", "text").
                    endObject().
                    startObject("age").
                        field("type", "integer").
                    endObject().
                    endObject().
                endObject();
        //2.创建request
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("person").settings(settings).mapping(mappings);
        //3.client执行request
        restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    }

创建文档:

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

响应结果:

【elastic search】JAVA操作elastic search,elastic search,JAVA EE,java,elasticsearch

修改文档:

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

删除文档:

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

响应结果:

【elastic search】JAVA操作elastic search,elastic search,JAVA EE,java,elasticsearch

搜索示例:

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

public class ElasticsearchSearchExample {

    public static void main(String[] args) {
        // 创建 RestHighLevelClient 实例,连接到 Elasticsearch 集群
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        // 构建搜索请求
        SearchRequest searchRequest = new SearchRequest("your_index"); // 替换为实际的索引名称

        // 构建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 查询所有文档

        // 设置一些可选参数
        searchSourceBuilder.from(0); // 设置起始索引,默认为0
        searchSourceBuilder.size(10); // 设置返回结果的数量,默认为10
        searchSourceBuilder.timeout(new TimeValue(5000)); // 设置超时时间,默认为1分钟

        // 将查询条件设置到搜索请求中
        searchRequest.source(searchSourceBuilder);

        try {
            // 执行搜索请求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            // 处理搜索响应
            System.out.println("Search took: " + searchResponse.getTook());

            // 获取搜索结果
            SearchHits hits = searchResponse.getHits();
            System.out.println("Total hits: " + hits.getTotalHits().value);

            // 遍历搜索结果
            for (SearchHit hit : hits.getHits()) {
                System.out.println("Document ID: " + hit.getId());
                System.out.println("Source: " + hit.getSourceAsString());
            }
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        } finally {
            try {
                // 关闭客户端连接
                client.close();
            } catch (IOException e) {
                // 处理关闭连接异常
                e.printStackTrace();
            }
        }
    }
}

请注意,上述示例中的 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

实体类:

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.Date;

@Document(indexName = "blogpost_index")
public class BlogPost {

    @Id
    private String id;

    @Field(type = FieldType.Text)
    private String title;

    @Field(type = FieldType.Text)
    private String content;

    @Field(type = FieldType.Keyword)
    private String author;

    @Field(type = FieldType.Date)
    private Date publishDate;

    // 构造函数、getter和setter

    public BlogPost() {
    }

    public BlogPost(String id, String title, String content, String author, Date publishDate) {
        this.id = id;
        this.title = title;
        this.content = content;
        this.author = author;
        this.publishDate = publishDate;
    }

    // 省略 getter 和 setter 方法
}

dao层:

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BlogPostRepository extends ElasticsearchRepository<BlogPost, String> {

    // 你可以在这里定义自定义查询方法

}

service层:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BlogPostService {

    private final BlogPostRepository blogPostRepository;

    @Autowired
    public BlogPostService(BlogPostRepository blogPostRepository) {
        this.blogPostRepository = blogPostRepository;
    }

    public BlogPost save(BlogPost blogPost) {
        return blogPostRepository.save(blogPost);
    }

    public Optional<BlogPost> findById(String id) {
        return blogPostRepository.findById(id);
    }

    public List<BlogPost> findAll() {
        return (List<BlogPost>) blogPostRepository.findAll();
    }

    public void deleteById(String id) {
        blogPostRepository.deleteById(id);
    }

}


 文章来源地址https://www.toymoban.com/news/detail-824450.html

到了这里,关于【elastic search】JAVA操作elastic search的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微服务分布式搜索引擎 Elastic Search RestClient 操作文档

    本文参考黑马 分布式Elastic search Elasticsearch是一款非常强大的开源搜索引擎,具备非常多强大功能,可以帮助我们从海量数据中快速找到需要的内容 初始化RestHighLevelClient 为了与索引库操作分离,我们再次参加一个测试类,做两件事情: 初始化RestHighLevelClient 我们的酒店数据

    2024年01月24日
    浏览(15)
  • 【Java EE 初阶】文件操作

    目录 1.什么是文件? 1.在cmd中查看指定目录的树形结构语法 2.文件路径 从当前目录开始找到目标程序(一个点) 返回到上一级目录,再找目标程序(两个点) 2.Java中文件操作 1.File概述 1.属性 2. 构造方法 3.常用方法  代码展示: 4.常用方法2 3. 文件内容的读写---数据流 1.I

    2024年02月06日
    浏览(17)
  • Elasticsearch:在 Java 客户端应用中管理索引 - Elastic Stack 8.x

    管理索引是客户端应用常用的一些动作,比如我们创建,删除,打开 及关闭索引等操作。在今天的文章中,我将描述如何在 Java 客户端应用中对索引进行管理。 我们需要阅读之前的文章 “Elasticsearch:在 Java 客户端中使用 truststore 来创建 HTTPS 连接”。在那篇文章中,我们详

    2023年04月09日
    浏览(16)
  • Java客户端调用elasticsearch进行深度分页查询 (search_after)

    前言 这是我在这个网站整理的笔记,有错误的地方请指出,关注我,接下来还会持续更新。 作者:神的孩子都在歌唱 具体的Search_after解释,可以看我这篇文章 elasticsearch 深度分页查询 Search_after(图文教程) 参考:https://blog.csdn.net/qq_44056652/article/details/126341810 作者:神的孩子

    2024年03月22日
    浏览(24)
  • elasticsearch | Exception in thread “main“ java.nio.file.NoSuchFileException: /usr/share/elastics

    使用 docker-compose 启动 elasticsearch 时,出现无法访问,如下图: 使用如下命令查看 一直处于重启状态。 使用命令查看日志 缺少 jvm.options 文件 解决: 将 docker-compose.yml 中挂载的数据卷 ( volumes ) 及其子项注释 : 然后使用命令重启 elasticsearch 将需要的文件从容器中拷出到宿主机

    2024年02月13日
    浏览(19)
  • Java操作es 查询时 [search_phase_execution_exception] all shards failed

    co.elastic.clients.elasticsearch._types.ElasticsearchException: [es/search] failed: [search_phase_execution_exception] all shards failed 以上异常来源于,在查询es数据时(反复横跳),按照月份分组统计数据,一开始查询一月份正常,但是查询别的月份由于数据量过多,导致后续数据只能查到某一天的, 于是我把代码

    2024年02月16日
    浏览(16)
  • elastic search入门

    参考1:Elastic Search 入门 - 知乎 参考2:Ubuntu上安装ElasticSearch_ubuntu elasticsearch-CSDN博客 1、ElasticSearch安装 1.1安装JDK,省略,之前已安装过 1.2创建ES用户 1.3 下载ElasticSearch安装包 Ubuntu上下载: 然后解压: 1.4配置 配置jvm.options 配置elasticsearch.yml: 根据以上设置的path.data和path.l

    2024年01月23日
    浏览(22)
  • Elastic Search一些用法

    参考: 中国开源社区 官方介绍 ES 的权重排序 【Elasticsearch】ElasticSearch 7.8 多字段权重排序 ElasticSearch7.3学习(十三)----定制动态映射(dynamic mapping) 【Elasticsearch教程4】Mapping 动态映射 【Elasticsearch教程5】Mapping 动态模板 Dynamic templates 注意事项:需要先创建模板,然后添加数据

    2024年02月06日
    浏览(19)
  • SpringCloud整合Elastic Search

    1、配置Elastic Search 注释说明: spring.elasticsearch.rest.uris :设置Elastic Search的连接地址,这里的示例是本地地址 http://localhost:9200 ,根据实际情况修改。 spring.elasticsearch.username 和 spring.elasticsearch.password :设置Elastic Search的用户名和密码,如果没有设置访问控制,这两项可以省略

    2024年02月15日
    浏览(17)
  • 【搜索引擎】elastic search核心概念

    前言 本文不涉及ES的具体安装下载、操作、集群的内容,这部分内容会放在后面一篇文章中。本文只包含ES的核心理论,看完本文再去学ES的细节会事半功倍。 目录 1.由日志存储引出的问题 2.什么是ES? 3.ES的数据结构 4.ES的核心原理 5.联系作者 本文或者说本系列的来源: 前面

    2024年02月03日
    浏览(17)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包