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多字段查询等

相关推荐
Data 31715 分钟前
经典sql题(二)求连续登录最多天数用户
大数据·数据库·数据仓库·sql·mysql
青云交2 小时前
大数据新视界 --大数据大厂之Kafka消息队列实战:实现高吞吐量数据传输
大数据·kafka·消息队列·高吞吐量·大数据新视界·技术奥秘·应用场景、新兴技术
成都古河云2 小时前
智慧园区:解析集成运维的未来之路
大数据·运维·人工智能·科技·5g·安全
深科信项目申报助手2 小时前
2024年国家高新申报,警惕被退回的情况
大数据·经验分享·科技·其他
lynn-fish2 小时前
蓝卓标杆客户镇洋发展,荣获IDC中国未来企业大奖
大数据·制造·智能制造·数字化·数字化转型·智能工厂·智能化
Gauss松鼠会2 小时前
GaussDB关键技术原理:高弹性(四)
java·大数据·网络·数据库·分布式·gaussdb
字节跳动数据平台2 小时前
火山引擎数智平台:高性能ChatBI的技术解读和落地实践
大数据·大模型·数据可视化·bi
samFuB4 小时前
【更新】上市公司-供应链金融水平数据(2000-2023年)
大数据·金融
tuantuan_tech4 小时前
开放式耳机哪个好用?开放式耳机好还是入耳式耳机好?
大数据·学习·生活·旅游·智能硬件
2301_793139334 小时前
光控资本:美股,又新高!比特币也大涨!静待“关键时刻”
大数据·人工智能