当前位置: 首页 > article >正文

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

前言:

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.kler.cn/a/282577.html

相关文章:

  • 如何在 Ubuntu 上配置 Kotlin 应用环境 ?
  • 北京大学c++程序设计听课笔记101
  • K8S 查看pod节点的磁盘和内存使用情况
  • Apache Paimon、Apache Hudi、Apache Iceberg对比分析
  • 论文阅读 - Causally Regularized Learning with Agnostic Data Selection
  • 深度解析 Feign
  • 计算机习题(一)
  • 【深度学习】迭代次数 vs bs? 迭代次数 vs epoch
  • 无线终端ZWS云应用(二)—DTU云的环境监测行业应用
  • Qt第二课----信号和槽
  • python把dbc转换成excel
  • 在Ubuntu 18.04上安装Linux、Nginx、MySQL、PHP(LEMP堆栈)的方法
  • 使用LinkedHashMap实现固定大小的LRU缓存
  • 【分享】7-Zip解压缩软件的4个功能模块
  • HarmonyOS NEXT未成年人模式无缝联动所有应用,过滤非适龄内容
  • centos中yum安装时提示Cannot find a valid baseurl for repo: base/7/x86_64 出现仓库源问题
  • 大模型知识检索RAG业务实践实践(初级篇)
  • 基于SpringBoot+Vue+MySQL的图书管理系统
  • Spring框架:从依赖注入到微服务
  • HTML5有格调的个人介绍网站源码
  • 产品经理如何提升系统思考能力
  • 商业律师事务所借助 DocuSign 解决方案加快了 QES 和身份识别流程 | 电子签约律师事务解决方案
  • Kotlin内联函数
  • BeautifulSoup:Python网页解析库详解
  • 数据结构(邓俊辉)学习笔记】串 14——BM_GS算法:构造gs表
  • Linux文件和目录常用命令