Elasticsearch——使用Java API实现ES中的索引、映射、文档操作(上)

本文涉及的产品
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: Elasticsearch——使用Java API实现ES中的索引、映射、文档操作 (上)

文章目录:


1.开篇

2.案例详解

2.1 创建ES客户端:完成与ES服务端的连接

2.2 创建索引

2.3 查看索引

2.4 删除索引

2.5 创建文档

2.6 修改文档

2.7 查看文档

2.8 删除文档

2.9 批量创建文档

1.开篇


在上一篇文章中,对ES中的创建/查看/删除索引、创建定义映射、创建/查看/修改/删除文档的这些操作有了一定的了解认识,但是是通过Postman + JSON串的方法来实现的。文章链接:https://blog.csdn.net/weixin_43823808/article/details/119911746

那么,这篇文章,仍然是对ES中的索引、映射、文档进行操作,只是方法换成了Java API

2.案例详解


首先需要创建一个maven工程,必然要添加ES相关的依赖。

同时双击ES安装目录的bin目录下的elasticsearch.bat ,先启动ES服务端。

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

2.1 创建ES客户端:完成与ES服务端的连接

后面的一二十个案例都是依照这个模板代码来的。

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
 *
 */
public class ESTestClient {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //关闭ES客户端
        esClient.close();
    }
}

2.2 创建索引

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import java.io.IOException;
/**
 *
 */
public class ESTestIndexCreate {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //创建索引 --- 请求对象
        CreateIndexRequest request = new CreateIndexRequest("user");
        //发送请求 --- 获取响应
        CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
        //响应状态
        boolean acknowledged = response.isAcknowledged();
        System.out.println("索引操作:" + acknowledged);
        //关闭ES客户端
        esClient.close();
    }
}


2.3 查看索引

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import java.io.IOException;
/**
 *
 */
public class ESTestIndexSearch {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //查询索引 --- 请求对象
        GetIndexRequest request = new GetIndexRequest("user");
        //发送请求 --- 获取响应
        GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
        //响应状态
        System.out.println(response.getAliases());
        System.out.println(response.getMappings());
        System.out.println(response.getSettings());
        //关闭ES客户端
        esClient.close();
    }
}


2.4 删除索引

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
 *
 */
public class ESTestIndexDelete {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //删除索引 --- 请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        //发送请求 --- 获取响应
        AcknowledgedResponse response = esClient.indices().delete(request,RequestOptions.DEFAULT);
        //响应状态
        System.out.println(response.isAcknowledged());
        //关闭ES客户端
        esClient.close();
    }
}


2.5 创建文档

索引有了,就相当于有了数据库。接下来就需要向数据库中建表、添加数据。建表自然要有表结构(有哪些属性、这些属性分别都是什么数据类型),也就是ES中的映射,在Java代码中就可以采用实体类来实现。

package com.szh.es;
/**
 *
 */
public class User {
    private String name;
    private String sex;
    private Integer age;
    //getter and setter
}
package com.szh.es;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
 *
 */
public class ESTestDocInsert {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //创建文档 --- 请求对象
        IndexRequest request = new IndexRequest();
        //设置索引及索引中文档的唯一性标识id(如果不指定,则ES会默认随机生成一个id)
        request.index("user").id("1001");
        //创建数据对象(文档内容)
        User user = new User();
        user.setName("张起灵");
        user.setSex("man");
        user.setAge(21);
        //向ES中插入数据,必须将数据格式转换为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String userJson = objectMapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);
        //发送请求 --- 获取响应
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        //关闭ES客户端
        esClient.close();
    }
}


2.6 修改文档


package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
 *
 */
public class ESTestDocUpdate {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //修改文档 --- 请求对象
        UpdateRequest request = new UpdateRequest();
        //配置修改参数 --- 表示要修改user索引中id为1001的文档内容
        request.index("user").id("1001");
        //将修改后的内容,以JSON格式写入请求体中
        request.doc(XContentType.JSON,"age",18);
        //发送请求 --- 获取响应
        UpdateResponse response = esClient.update(request,RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        //关闭ES客户端
        esClient.close();
    }
}


2.7 查看文档

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
 *
 */
public class ESTestDocSearch {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //查询文档 --- 请求对象
        GetRequest request = new GetRequest();
        //设置请求参数 --- 表示要查询user索引中id为1001的文档内容
        request.index("user").id("1001");
        //发送请求 --- 获取响应
        GetResponse response = esClient.get(request,RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        //关闭ES客户端
        esClient.close();
    }
}


2.8 删除文档

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
 *
 */
public class ESTestDocDelete {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //删除文档 --- 请求对象
        DeleteRequest request = new DeleteRequest();
        //设置请求参数 --- 表示要删除user索引中id为1001的文档
        request.index("user").id("1001");
        //发送请求 --- 获取响应
        DeleteResponse response = esClient.delete(request,RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        //关闭ES客户端
        esClient.close();
    }
}


2.9 批量创建文档

package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
 *
 */
public class ESTestDocInsertBatch {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //批量新增文档 --- 请求对象
        BulkRequest request = new BulkRequest();
        //以JSON格式批量新增文档 --- 存入请求体中
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张起灵","sex","boy","age",21));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "小哥","sex","boy","age",18));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "小宋","sex","boy","age",20));
        //发送请求 --- 获取响应
        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        //关闭ES客户端
        esClient.close();
    }
}

相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
相关文章
|
1月前
|
JSON API 数据格式
小红书API接口文档:笔记详情数据开发手册
小红书笔记详情API可获取指定笔记的标题、正文、互动数据及多媒体资源,支持字段筛选与评论加载。通过note_id和access_token发起GET/POST请求,配合签名验证,广泛用于内容分析与营销优化。
|
2月前
|
人工智能 安全 架构师
告别旅行规划的"需求文档地狱"!这个AI提示词库,让你像调API一样定制完美旅程
作为开发者,旅行规划如同“需求地狱”:信息碎片、需求多变、缺乏测试。本文提出一套“企业级”AI提示词库,将模糊需求转化为结构化“API请求”,实现标准化输入输出,让AI成为你的专属旅行架构师,30分钟生成专业定制方案,提升决策质量,降低90%时间成本。
495 129
|
6月前
|
JSON 安全 数据可视化
Elasticsearch(es)在Windows系统上的安装与部署(含Kibana)
Kibana 是 Elastic Stack(原 ELK Stack)中的核心数据可视化工具,主要与 Elasticsearch 配合使用,提供强大的数据探索、分析和展示功能。elasticsearch安装在windows上一般是zip文件,解压到对应目录。文件,elasticsearch8.x以上版本是自动开启安全认证的。kibana安装在windows上一般是zip文件,解压到对应目录。elasticsearch的默认端口是9200,访问。默认用户是elastic,密码需要重置。
3186 0
|
8月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
10月前
|
JavaScript Java 测试技术
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
|
10月前
|
API 开发者
通义灵码 API 开发文档自动生成场景DEMO
通义灵码API开发文档自动生成场景DEMO展示了通过自定义指令,大模型能快速根据类代码生成Markdown格式的API文档。文档详细描述API的入参、出参,并可生成测试代码等示例,帮助开发者快速创建美观的API文档。
572 1
|
10月前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
187 14
|
11月前
|
存储 缓存 监控
极致 ElasticSearch 调优,让你的ES 狂飙100倍!
尼恩分享了一篇关于提升Elasticsearch集群的整体性能和稳定性措施的文章。他从硬件、系统、JVM、集群、索引和查询等多个层面对ES的性能优化进行分析,帮助读者提升技术水平。
|
安全 Java 索引
java映射(map用法)
主要分两个接口:collection和Map 主要分三类:集合(set)、列表(List)、映射(Map)1.集合:没有重复对象,没有特定排序方式2.列表:对象按索引位置排序,可以有重复对象3.映射:有一个键对象和一个值对象,键不可重复,值可以重复 hashtable 和hashmap区别 1 HashMap不是线程安全的 2   HashTable是线程安全的一个Collection。
913 0
|
1月前
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
141 1
下一篇
oss云网关配置