elasticsearch整合java使用创建索引、指定索引映射、操作添加文档、删除文档、更新文档、批量操作

news2024/9/29 22:57:45

前言:

elasticsearch的整合流程可以参考:Elasticsearch7.15版本后新版本的接入-CSDN博客

索引

1.创建索引

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        
        boolean exists = elasticsearchClient.indices().exists(query -> query.index("new_ceshi")).value();
        System.out.println(exists);
        if (exists) {
            System.out.println("已存在");
        } else {
            final CreateIndexResponse products = elasticsearchClient.indices().create(builder -> builder.index("new_ceshi"));
            System.out.println(products.acknowledged());
        }

    }

2.查询索引

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();

        GetIndexResponse products = elasticsearchClient.indices().get(query -> query.index("new_ceshi"));
        System.out.println(products.toString());
    }

3.删除索引

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        boolean exists = elasticsearchClient.indices().exists(query -> query.index("new_ceshi")).value();
        System.out.println(exists);
        if (exists) {
            DeleteIndexResponse response = elasticsearchClient.indices().delete(query -> query.index("new_ceshi"));
            System.out.println(response.acknowledged());
        } else {
            System.out.println("索引不存在");
        }
    }

索引映射 

4.查询索引的映射

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        GetIndexResponse response = elasticsearchClient.indices().get(builder -> builder.index("new_bank"));
        System.out.println(response.result().get("new_bank").mappings().toString());
    }

5.创建索引以及初始化索引映射

    @Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        elasticsearchClient.indices()
                .create(builder -> builder.index("new_product")
                        .mappings(map -> map.properties("name", p -> p.text(textProperty -> textProperty.analyzer("ik_max_word").searchAnalyzer("ik_max_word")))
                                .properties("intro", p -> p.text(textProperty -> textProperty.analyzer("ik_max_word").searchAnalyzer("ik_max_word")))
                                .properties("stock", p -> p.integer(integerProperty -> integerProperty)))
                );
    }

文档 

6.创建文档-自定义类数据存储容器

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        Produce produce = new Produce("饼干", "上好的饼干", 2000);
        IndexResponse response = elasticsearchClient.index(builder -> builder.index("new_product").id("1").document(produce));
        System.err.println(response.version());
    }

结果:

7.创建文档-HashMap存储容器

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        HashMap<String, Object> doc = new HashMap<>();
        doc.put("name","油条");
        doc.put("intro","纯油炸的油条");
        doc.put("stock","999");
        final IndexResponse response = elasticsearchClient.index(builder -> builder.index("new_product").id("2").document(doc));
    }

8.查询所有文档

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        SearchResponse<Object> response = elasticsearchClient.search(builder -> builder.index("new_product"), Object.class);
        List<Hit<Object>> hits = response.hits().hits();
        hits.forEach(
                x-> System.out.println(x.toString())
        );
    }

9.查询某个id的文档

  @Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        GetRequest new_product = new GetRequest.Builder()
                .index("new_product")
                .id("1")
                .build();
        GetResponse<Object> objectGetResponse = elasticsearchClient.get(new_product, Object.class);
        System.out.printf("objectGetResponse=========="+objectGetResponse.source());
    }

10删除文档

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        //删除文档
        DeleteRequest new_product = new DeleteRequest.Builder()
                .index("new_product")
                .id("1")
                .build();
        DeleteResponse delete = elasticsearchClient.delete(new_product);
        System.out.printf("delete==========" + delete);
    }

 11.更新文档-自定义类

        全更新

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        Produce produce = new Produce("铁锤", "全刚的大铁锤", 666);
        UpdateResponse<Produce> new_product = elasticsearchClient.update(builder -> builder.index("new_product").id("2").doc(produce), Produce.class);
        System.err.println(new_product.shards().successful());
    }

        指定字段修改.docAsUpsert(true)

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        Produce produce = new Produce();
        produce.setName("小铁锤");
        UpdateResponse<Produce> new_product = elasticsearchClient.update(builder -> builder.index("new_product").id("2").docAsUpsert(true).doc(produce), Produce.class);
        System.err.println(new_product.shards().successful());
    }

12更新文档-Map更新

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        Map<String, Object> updateJson = new HashMap<>();
        updateJson.put("name","巨大铁锤");

        UpdateRequest<Object, Object> updateRequest = new UpdateRequest.Builder<>()
                .index("new_product")
                .id("2")
                .doc(updateJson)
                .build();
        UpdateResponse<Object> updateResponse = elasticsearchClient.update(updateRequest, Object.class);
        System.out.println("Document updated: " + updateResponse.result());
    }

批量操作

13批量添加

@Test
    public void contextLoads() throws IOException {
        ElasticsearchClient elasticsearchClient = elasticSearchConfig.esRestClient();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        BulkRequest.Builder br = new BulkRequest.Builder();
        for (SkuEsModel skuEsModel : skuEsModels) {
            br.operations(op->op.index(idx->idx.index("produces").id(String.valueOf(skuEsModel.getSkuId())).document(skuEsModel)));
        }
        BulkResponse response = elasticsearchClient.bulk(br.build());
    }

 

复杂检索请查看:elasticsearch复杂检索,match、matchAll、matchPhrase、term、多条件查询、multiMatch多字段查询等

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2087666.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Qt】表单布局QFormLayout

表单布局QFormLayout Qt 还提供了 QFormLayout , 属于是 QGridLayout 的特殊情况, 专⻔⽤于实现两列表单的布局. 这种表单布局多⽤于让⽤⼾填写信息的场景. 左侧列为提⽰, 右侧列为输⼊框 例子&#xff1a;使用QFormLayout创建表单 &#xff08;1&#xff09;设置三个label、…

数据分析及应用:如何对试卷得分做min-max归一化处理?

目录 0 问题描述 1 数据准备 2 问题分析 3 小结 0 问题描述 现有试卷信息表examination_info(exam_id试卷ID, tag试卷类别, difficulty试卷难度, duration考试时长, release_time发布时间): 试卷作答记录表exam_record(uid用户ID, exam_id试卷ID, start_time开始作答时…

强者和弱者的区别体现在面对失败上

面对成功&#xff0c;面对日常&#xff0c;每一个人都是谦谦君子温文尔雅&#xff0c;谈论困难挫折&#xff0c;不屑一顾。 这是他们的真实面目吗&#xff1f; 有的是真的&#xff0c;有的是假的。 强者视失败为磨砺意志的砥石&#xff0c;他们勇于承认不足&#xff0c;积极寻…

物联网架构之CDH集群部署

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:Linux运维老纪的首页…

中国各地区-交通运输-电信业务总量(1999-2020年)

电信业务总量是指以货币形式表示的电信企业为社会提供的各类电信服务的总数量&#xff0c;包含了各类电信业务&#xff0c;如固定电话、移动电话、数据通信、互联网接入等。 1999-2020年 中国各地区-交通运输-电信业务总量 指标 年份、地区、交通运输-电信业务总量(亿元)。 …

2024年8月29日(harbor似有仓库管理,Docker-compose容器编排)

一、harbor私有仓库管理 yum -y install epel-release yum -y install python2-pip pip install --upgrade pip pip list pip 8x pip install --upgrade pip pip install --upgrade pip20.3 -i https://mirrors.aliyun.com/pypi/simple pip list pip install docker-compo…

基于my Batis优化图书管理系统(总)

1.准备工作 1.1 数据库表设计 -- 创建数据库 DROP DATABASE IF EXISTS book_manage;CREATE DATABASE book_manage DEFAULT CHARACTER SET utf8mb4; use book_manage;-- 用户表 DROP TABLE IF EXISTS user_info; CREATE TABLE user_info (id INT NOT NULL AUTO_INCREMENT,use…

网站建设完成后, 功能性网站如何做seo

功能性网站的SEO优化关注于提高网站在搜索引擎中的排名&#xff0c;从而吸引更多用户并提升用户体验。以下是功能性网站SEO的详细解析&#xff1a; 关键词研究与布局 目标受众分析&#xff1a;了解目标受众的搜索习惯和需求&#xff0c;确定适合的关键词。使用工具如Google Ke…

反弹shell流量分析与检测

常用的隧道技术&#xff1a; 网络层&#xff1a;ipv6、Icmp、gre IPv6隧道&#xff1a;将ipv6报文放入ipv4作为载体进行传输&#xff0c;工具&#xff1a;socat、6tunnel ICMP隧道&#xff1a;将数据放入ping包中进行传输&#xff0c;工具&#xff1a;icmpsh、PingTunnel G…

日本麻将入门(二):牌效率【基础】

基础牌效率 引入 日麻&#xff0c;又称立直麻将。日麻的水平本质上与你是否会立直有很大关系&#xff08;参见常用役种&#xff1a;立直&#xff1a;优点&#xff09;&#xff0c;但立直最大的缺点就是不能副露&#xff0c;导致我们只能通过自己的摸切来完成听牌形的组成。在…

20. 筛选dataframe

哈喽&#xff0c;大家好&#xff0c;我是木头左&#xff01; 筛选条件 基本筛选 要筛选DataFrame&#xff0c;首先需要了解筛选条件。Pandas提供了多种筛选条件&#xff0c;包括等于&#xff08;&#xff09;、不等于&#xff08;&#xff01;&#xff09;、大于&#xff08;…

Leetcode Day14排序算法

动态git可以看 :https://leetcode.cn/problems/sort-an-array/solutions/179370/python-shi-xian-de-shi-da-jing-dian-pai-xu-suan-fa/ 选择排序 def selection_sort(nums):n len(nums)for i in range(n):for j in range(i, n):if nums[i] > nums[j]:nums[i], nums[j] …

05.整合Axios+MockJs

1. 前言 作为前后端分离的项目&#xff0c;必不可少的当然是发请求向后端拿数据了&#xff0c; 但是不可能每次等到接口完成我们才开始开发前端&#xff0c;所以使用 mock.js 先模拟后端接口&#xff0c;等后端接口开发完成后&#xff0c;可以无缝衔接&#xff0c;直接替换为真…

EmguCV学习笔记 VB.Net 7.2 特征点检测

版权声明&#xff1a;本文为博主原创文章&#xff0c;转载请在显著位置标明本文出处以及作者网名&#xff0c;未经作者允许不得用于商业目的。 EmguCV是一个基于OpenCV的开源免费的跨平台计算机视觉库,它向C#和VB.NET开发者提供了OpenCV库的大部分功能。 教程VB.net版本请访问…

(24)(24.6) 基于OSD的参数菜单

文章目录 前言 1 Copter默认屏幕 2 Plane默认屏幕 3 实例 前言 这允许使用 ArduPilot 机载 OSD 和 RC 发射机的杆输入设置和调整参数。还有两个额外的 OSD 屏幕可用&#xff08;OSD5 和 OSD6&#xff09;&#xff0c;每个屏幕有 9 个“插槽”来保存参数。屏幕首先显示一组…

taro ui 小程序at-calendar日历组件自定义样式+选择范围日历崩溃处理

taro ui 日历文档 目录 单选标记时间&#xff1a; 效果&#xff1a; template&#xff1a; data&#xff1a; methods: 日历--范围选择&#xff1a; 效果&#xff1a; template&#xff1a; data&#xff1a; methods&#xff1a; 日历--间隔多选&#xff1a;利用标…

详细分析python中QRCode生成二维码的基本知识(附Demo)

目录 前言1. 基本知识2. Demo3. 彩蛋3.1 文件路径3.2 Image.LANCZOS 前言 以下主要利用python中的QRCode来生成二维码的基本知识 1. 基本知识 简单易用&#xff0c;并且可以生成高质量的二维码图像 支持多种自定义设置&#xff0c;例如二维码的大小、边框、容错级别、颜色等…

java在项目中实现excel导入导出

一、初识EasyExcel* 1. Apache POI 先说POI&#xff0c;有过报表导入导出经验的同学&#xff0c;应该听过或者使用。 Apache POI是Apache软件基金会的开源函式库&#xff0c;提供跨平台的Java API实现Microsoft Office格式档案读写。但是存在如下一些问题&#xff1a; 1.1 …

C语言阴阳迷宫

目录 开头程序程序的流程图程序游玩的效果下一篇博客要说的东西 开头 大家好&#xff0c;我叫这是我58。 程序 #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Windows.h> enum WASD {W…

【传输层协议】TCP协议(上) {TCP协议段格式;确认应答机制;超时重传机制;连接管理机制:三次握手、四次挥手}

TCP&#xff08;Transmission Control Protocol&#xff09;是一种面向连接的、可靠的、基于字节流的传输层协议&#xff0c;用于在网络上可靠地传输数据。TCP是互联网协议套件&#xff08;TCP/IP&#xff09;中的一个主要协议&#xff0c;它在IP&#xff08;Internet Protocol…