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

前言:

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

索引

1.创建索引

java 复制代码
@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.查询索引

java 复制代码
@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.删除索引

java 复制代码
@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.查询索引的映射

java 复制代码
@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.创建索引以及初始化索引映射

java 复制代码
    @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.创建文档-自定义类数据存储容器

java 复制代码
@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存储容器

java 复制代码
@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.查询所有文档

java 复制代码
@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的文档

java 复制代码
  @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删除文档

java 复制代码
@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.更新文档-自定义类

全更新

java 复制代码
@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)

java 复制代码
@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更新

java 复制代码
@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批量添加

java 复制代码
@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多字段查询等

相关推荐
幽弥千月1 小时前
【ELK】ES单节点升级为集群并开启https【亲测可用】
elk·elasticsearch·https
运维&陈同学1 小时前
【Elasticsearch05】企业级日志分析系统ELK之集群工作原理
运维·开发语言·后端·python·elasticsearch·自动化·jenkins·哈希算法
ssxueyi10 小时前
如何查看flink错误信息
大数据·flink
奥顺12 小时前
PHP与AJAX:实现动态网页的完美结合
大数据·mysql·开源·php
中东大鹅14 小时前
分布式数据存储基础与HDFS操作实践
大数据·linux·hadoop·分布式·hbase
Y编程小白15 小时前
Git版本控制工具--基础命令和分支管理
大数据·git·elasticsearch
jingling55516 小时前
如何使用免费资源--知网篇
开发语言·经验分享·搜索引擎·pdf·开源
不爱学习的YY酱16 小时前
【操作系统不挂科】<内存管理-文件系统实现(18)>选择题(带答案与解析)
java·大数据·数据库
guanpinkeji17 小时前
陪诊小程序搭建,打造一站式陪诊服务
大数据·小程序·小程序开发·陪诊·陪诊小程序
胡耀超17 小时前
如何从全局视角规划项目与战略决策(“精准接送”案例、技术架构设计与选型、业务逻辑及产品商业模式探讨)
大数据·数据挖掘·软件架构·商业模式·数据管理