SpringBoot -ElasticSearch RestHighLevelClient 高级客户端使用(2) Index操作

前一章讲过如何将SpringBoot -ElasticSearch的高级客户端RestHighLevelClient 整合

这一章是使用RestHighLevelClient 进行Index操作

ElasticSearch计划7.X移出type,不再有type的操作,所有本文中将type和Index名称设置为相同的名字.

官方API地址Java High Level REST Client

这篇就关于使用RestClient操作索引,内容就是解决问题的实例。同样,一切版本以6.4.2为准。其他升级版本新的api不属此列。

 

添加Index

由于使用RestHighLevelClient(后称为rhlClient)时,进行Index操作,所有IndexRequest都会校验Index,type,source,contentType不为空。

所有构建创建Index创建请求时需要将Index,type,source,contentType配置完整

因为整合了ik中文分词器,所以“analyzer”: “ik_max_word”此处参考安装配置ik分词器

public boolean indexCreate() {
        try {
            CreateIndexRequest index = new CreateIndexRequest("index_name");
            Map<String,Object> properties = Maps.newHashMap();
            Map<String,Object> propertie = Maps.newHashMap();
            propertie.put("type","text");
            propertie.put("index",true);
            propertie.put("analyzer","ik_max_word");
            properties.put("field_name",propertie);
            
            XContentBuilder builder = JsonXContent.contentBuilder();
            builder.startObject()
                        .startObject("mappings")
                            .startObject("index_name")
                                .field("properties",properties)
                            .endObject()
                        .endObject()
                        .startObject("settings")
                            .field("number_of_shards",3)
                            .field("number_of_replicas",1)
                        .endObject()
                    .endObject();
            index.source(builder);
            rhlClient.indices().create(index,RequestOptions.DEFAULT);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
       
    }

判断Index是否存在

public boolean indexExists(String indexName) {
        GetIndexRequest request = new GetIndexRequest();
        request.indices(indexName);
        try {
            return rhlClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

删除Index

public boolean deleteIndex(String indexName) {
        DeleteIndexRequest index = new DeleteIndexRequest(indexName);
        try {
            rhlClient.indices().delete(index);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
      
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值