美文网首页
Elasticsearch——JavaApi实现索引管理

Elasticsearch——JavaApi实现索引管理

作者: 小波同学 | 来源:发表于2020-11-14 17:50 被阅读0次

版本

不同版本的elasticsearch-rest-high-level-client和 elasticsearch之间存在兼容风险,请确保和elasticsearch版本一致,否则会出现无法预计的错误。

es配置

maven依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.3.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.3.0</version>
</dependency>

配置application.properties

spring.application.name=service-search

#多个节点用逗号隔开
elasticsearch.hostlist=127.0.0.1:9200

创建配置类ElasticsearchConfig

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.hostlist}")
    private String hostlist;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient(){
        String[] split = hostlist.split(",");
        HttpHost[] httpHost = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String[] item = split[i].split(":");
            httpHost[i] = new HttpHost(item[0],Integer.parseInt(item[1]),"http");
        }
        return new RestHighLevelClient(RestClient.builder(httpHost));
    }
}

索引管理测试代码

同步新增索引

PUT /my_index

{
    "settings":{
        "number_of_shards": "1",
        "number_of_replicas": "1"
    },
    "mappings":{
        "properties":{
            "field1":{
                "type": "text"
            },
            "field2":{
                "type": "text"
            }
        }
    },
    "aliases":{
        "default_index":{}
    }
}
@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
@Slf4j
public class TestIndex {

    @Autowired
    private RestHighLevelClient client;

    //新增索引
    @Test
    public void testCreateIndex() throws IOException {
        /*PUT /my_index
        {
            "settings":{
                "number_of_shards": "1",
                        "number_of_replicas": "1"
            },
                "mappings":{
                "properties":{
                    "field1":{
                        "type": "text"
                    },
                    "field2":{
                        "type": "text"
                    }
                }
            },
                "aliases":{
                "default_index":{}
            }
        }*/

        //1、构建请求
        CreateIndexRequest indexRequest = new CreateIndexRequest("my_index");
        //设置参数
        indexRequest.settings(Settings.builder()
                .put("number_of_shards","1")
                .put("number_of_replicas","1").build());

        //--------------------设置映射的三种方式-------------------------
        //设置映射方式1
        indexRequest.mapping("{" +
                "  \"properties\":{" +
                "    \"field1\":{\"type\": \"text\"}," +
                "    \"field2\":{\"type\": \"text\"}" +
                "  }" +
                "}", XContentType.JSON);

        //设置映射方式2
        Map<String,Object> field1 = new HashMap<>();
        field1.put("type","text");
        field1.put("analyzer","standard");
        Map<String,Object> field2 = new HashMap<>();
        field2.put("type","text");
        Map<String,Object> properties = new HashMap<>();
        properties.put("field1",field1);
        properties.put("field2",field2);
        Map<String,Object> mapping = new HashMap<>();
        mapping.put("properties",properties);
        indexRequest.mapping(mapping);

        //设置映射方式3
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.startObject("properties");
            {
                builder.startObject("field1");
                {
                    builder.field("type","text");
                }
                builder.endObject();
                builder.startObject("field2");
                {
                    builder.field("type","text");
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
        indexRequest.mapping(builder);

        //创建别名
        indexRequest.alias(new Alias("pro_index"));

        //-------------------------可选参数------------------------
        //超时时间
        indexRequest.setTimeout(TimeValue.timeValueSeconds(5));

        //主节点超时时间
        indexRequest.setMasterTimeout(TimeValue.timeValueSeconds(5));

        //设置创建索引API返回相应之前等待活动分片的数量
        indexRequest.waitForActiveShards(ActiveShardCount.ONE);

        //2、执行
        //操作索引的客户端
        IndicesClient indices = client.indices();
        CreateIndexResponse indexResponse = indices.create(indexRequest, RequestOptions.DEFAULT);

        //3、获取结果
        //得到相应
        boolean acknowledged = indexResponse.isAcknowledged();
        //指示是否在超时前为索引中的每个分片启动了所需数量的碎片副本
        boolean shardsAcknowledged = indexResponse.isShardsAcknowledged();
        System.out.println("acknowledged: "+acknowledged);
        System.out.println("shardsAcknowledged: "+shardsAcknowledged);
    }
}

异步新增索引

@Test
public void testCreateIndexAsync() throws IOException {

    //1、构建请求
    CreateIndexRequest indexRequest = new CreateIndexRequest("my_index");
    //设置参数
    indexRequest.settings(Settings.builder()
            .put("number_of_shards","1")
            .put("number_of_replicas","1").build());

    //--------------------设置映射的三种方式-------------------------
    //设置映射方式1
    indexRequest.mapping("{" +
            "  \"properties\":{" +
            "    \"field1\":{\"type\": \"text\"}," +
            "    \"field2\":{\"type\": \"text\"}" +
            "  }" +
            "}", XContentType.JSON);

    //设置映射方式2
    Map<String,Object> field1 = new HashMap<>();
    field1.put("type","text");
    field1.put("analyzer","standard");
    Map<String,Object> field2 = new HashMap<>();
    field2.put("type","text");
    Map<String,Object> properties = new HashMap<>();
    properties.put("field1",field1);
    properties.put("field2",field2);
    Map<String,Object> mapping = new HashMap<>();
    mapping.put("properties",properties);
    indexRequest.mapping(mapping);

    //设置映射方式3
    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.startObject("properties");
        {
            builder.startObject("field1");
            {
                builder.field("type","text");
            }
            builder.endObject();
            builder.startObject("field2");
            {
                builder.field("type","text");
            }
            builder.endObject();
        }
        builder.endObject();
    }
    builder.endObject();
    indexRequest.mapping(builder);

    //创建别名
    indexRequest.alias(new Alias("pro_index"));

    //-------------------------可选参数------------------------
    //超时时间
    indexRequest.setTimeout(TimeValue.timeValueSeconds(5));

    //主节点超时时间
    indexRequest.setMasterTimeout(TimeValue.timeValueSeconds(5));

    //设置创建索引API返回相应之前等待活动分片的数量
    indexRequest.waitForActiveShards(ActiveShardCount.ONE);

    //2、执行
    ActionListener<CreateIndexResponse> listener = new ActionListener<CreateIndexResponse>() {
        @Override
        public void onResponse(CreateIndexResponse createIndexResponse) {
            //3、获取结果
            //得到相应
            boolean acknowledged = createIndexResponse.isAcknowledged();
            //指示是否在超时前为索引中的每个分片启动了所需数量的碎片副本
            boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();
            System.out.println("acknowledged: "+acknowledged);
            System.out.println("shardsAcknowledged: "+shardsAcknowledged);
        }

        @Override
        public void onFailure(Exception e) {
            log.error("error",e);
        }
    };

    client.indices().createAsync(indexRequest, RequestOptions.DEFAULT,listener);

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

同步删除索引

@Test
public void testDeleteIndex() throws IOException {
    //创建删除索引请求
    DeleteIndexRequest indexRequest = new DeleteIndexRequest("my_book");
    //执行
    AcknowledgedResponse delete = client.indices().delete(indexRequest, RequestOptions.DEFAULT);
    //获取响应
    boolean acknowledged = delete.isAcknowledged();
    System.out.println("acknowledged: "+acknowledged);
}

异步删除索引

@Test
public void testDeleteIndexAsync() throws IOException {
    //创建删除索引请求
    DeleteIndexRequest indexRequest = new DeleteIndexRequest("my_book");
    ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
        @Override
        public void onResponse(AcknowledgedResponse acknowledgedResponse) {
            //获取响应
            boolean acknowledged = acknowledgedResponse.isAcknowledged();
            System.out.println("acknowledged: "+acknowledged);
        }

        @Override
        public void onFailure(Exception e) {
            log.error("error",e);
        }
    };
    //执行
    client.indices().delete(indexRequest, RequestOptions.DEFAULT);
}

判断索引是否存在

@Test
public void testExistIndex() throws IOException {
    GetIndexRequest request = new GetIndexRequest("my_book");
    //参数
    request.local();//从主节点返回本地索引信息状态
    request.humanReadable(true);//以适合人类的格式返回
    request.includeDefaults(false);//是否返回每个索引的所有默认配置

    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println("index exists: "+exists);
}

关闭索引

@Test
public void testCloseIndex() throws IOException {
    CloseIndexRequest request = new CloseIndexRequest("my_book");
    AcknowledgedResponse close = client.indices().close(request, RequestOptions.DEFAULT);
    boolean acknowledged = close.isAcknowledged();
    System.out.println("acknowledged: "+acknowledged);
}

开启索引

@Test
public void testOpenIndex() throws IOException {
    OpenIndexRequest request = new OpenIndexRequest("my_book");
    OpenIndexResponse open = client.indices().open(request, RequestOptions.DEFAULT);
    boolean acknowledged = open.isAcknowledged();
    System.out.println("index open: "+acknowledged);
}

相关文章

网友评论

      本文标题:Elasticsearch——JavaApi实现索引管理

      本文链接:https://www.haomeiwen.com/subject/liewbktx.html