Elasticsearch整合-续集-index

该博客介绍了如何在Java应用中配置Elasticsearch的RestHighLevelClient,包括设置HTTP主机和端口。同时展示了如何创建IndexRequest,通过序列化对象的方式填充数据,并执行索引操作。还提供了请求选项的静态常量设置,如添加认证头和响应消费者工厂。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在配置类中继续添加配置
相关配置的官网地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.4/java-rest-low-usage-requests.html#java-rest-low-usage-request-options

当前配置类:

@Configuration
public class VmElasticsearchConfig {

    @Bean
    public RestHighLevelClient esRestClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.23.145", 9200, "http")));
                        //没有集群不用指定多个
//                        new HttpHost("localhost", 9201, "http"))
        return client;
    }

    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builderbuilder=RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }
}

测试添加:
文档地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.4/java-rest-high-document-index.html
有多种方式,详情见文档

index测试:

  @Test
    public void indexData() throws IOException {
      IndexRequest indexRequest = new IndexRequest("users");
      indexRequest.id("1");//数据的id
//      indexRequest.source("userName","zhangsan","age","18");  第一种方式
        User user = new User();
        user.setUserName("zhangsan");
        user.setAge(18);
        user.setGender("男");
        String jsonString = JSON.toJSONString(user);
        indexRequest.source(jsonString, XContentType.JSON);//数据的内容

        //执行操作
        IndexResponse index = client.index(indexRequest, VmElasticsearchConfig.COMMON_OPTIONS);

        //提取有用的响应数据
        System.out.println(index);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值