ElasticSearch 索引相关操作

来源:互联网 发布:php仿百度文库源码 编辑:程序博客网 时间:2024/05/21 21:48

0 概述

本文主要介绍基于ElasticSearch 5.0 客户端模式开发~,可能遇到的问题:常见的问题以及解决方案

1依赖pom

    <dependencies>        <dependency>            <groupId>org.elasticsearch.client</groupId>            <artifactId>transport</artifactId>            <version>5.0.0</version>        </dependency>        <!--log4j2 这个是强依赖-->        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-api</artifactId>            <version>2.6.2</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-core</artifactId>            <version>2.6.2</version>        </dependency>        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>fastjson</artifactId>            <version>1.2.29</version>        </dependency>    </dependencies>

2传输实例工厂

import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.elasticsearch.transport.client.PreBuiltTransportClient;import java.net.InetAddress;/** * Created by hsc on 17/4/8. */public class ESClient {    /**     * es 客户端传输实例     */    private static TransportClient client;    public static TransportClient getInstance() {        if (client == null) {            synchronized (ESClient.class) {                try {                    Settings settings = Settings.builder()                            .put("cluster.name", "hsc.test")                            .put("client.transport.sniff", true).build();                    client = new PreBuiltTransportClient(settings)                            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));                } catch (Exception ex) {                    System.out.println(ex.getMessage());                }            }        }        return client;    }}

值得说明是:

  • 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中, 这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端,它会自动帮你添加,并且自动发现新加入集群的机器。
  • 如果集群名称不是默认的”elasticsearch”,就需要给出集群名称
    具体见官网

3 索引相关操作

import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse;import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;import org.elasticsearch.action.admin.indices.get.GetIndexResponse;import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;import org.elasticsearch.cluster.metadata.MappingMetaData;import org.elasticsearch.common.collect.ImmutableOpenMap;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.xcontent.XContentBuilder;import org.elasticsearch.common.xcontent.XContentFactory;import java.io.IOException;/** * Created by hsc on 17/4/8. */public final class ESIndexOperations {    public static Boolean createIndex(String index) {        //设置主分片和副本数量        if (isExists(index)) {            System.out.println("index has existed" + index);            return false;        }        Settings settings = Settings.builder()                .put("number_of_shards", 4)                .put("number_of_replicas", 1)                .build();        CreateIndexResponse response = ESClient.getInstance().admin().indices()                .prepareCreate(index)                .setSettings(settings).get();        return response.isAcknowledged();    }    public static boolean isExists(String index) {        IndicesExistsResponse existsResponse = ESClient.getInstance().admin().indices().prepareExists(index)                .get();        return existsResponse.isExists();    }    //根据索引名字删除索引    public static boolean deleteIndex(String index) {        if (!isExists(index)) {            return false;        }        DeleteIndexResponse response = ESClient.getInstance().admin().indices().                delete(new DeleteIndexRequest(index)).actionGet();        return response.isAcknowledged();    }    //查询索引    public static String[] queryIndex() {        GetIndexResponse response = ESClient.getInstance().admin().                indices().prepareGetIndex().get();        return response.indices();    }    //创建indexMapping    public static boolean createIndexMapping(String index, String type) throws IOException {        XContentBuilder mapBuilder = XContentFactory.jsonBuilder();        mapBuilder.startObject().startObject("properties")                .startObject("userId")                .field("type", "string")                .field("index", "not_analyzed")                .endObject().endObject().endObject();        PutMappingResponse response = ESClient.getInstance().admin().indices().                preparePutMapping(index)                .setType(type)                .setSource(mapBuilder).get();        return response.isAcknowledged();    }    public static ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> getIndexMapping(String index) throws IOException {        GetMappingsResponse response = ESClient.getInstance().admin().indices().                prepareGetMappings(index)                .get();        return response.getMappings();    }    //为索引添加一个别名    public static boolean addAliasForIndex(String index, String alias) {        IndicesAliasesResponse response = ESClient.getInstance().admin().indices()                .prepareAliases().addAlias(index, alias).execute().actionGet();        return response.isAcknowledged();    }}

4 测试程序

import com.alibaba.fastjson.JSON;import org.elasticsearch.cluster.metadata.MappingMetaData;import org.elasticsearch.common.collect.ImmutableOpenMap;import java.io.IOException;import java.util.Iterator;/** * Created by hsc on 17/4/9. */public class TestMain {    public static void main(String[] args) throws Exception {        System.out.println(ESIndexOperations.createIndex("index_test"));        System.out.println(ESIndexOperations.deleteIndex("index_test"));        System.out.println(ESIndexOperations.createIndex("index_test"));        System.out.println(JSON.toJSON(ESIndexOperations.queryIndex()));        System.out.println(ESIndexOperations.createIndexMapping("index_test", "test"));        printIndexMapping(ESIndexOperations.getIndexMapping("index_test"));    }    public static void printIndexMapping(ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> indexMapping) throws IOException {        if (indexMapping == null) {            return;        }        Iterator<String> stringIterator = indexMapping.keysIt();        while (stringIterator.hasNext()) {            ImmutableOpenMap<String, MappingMetaData> type = indexMapping.get(stringIterator.next());            Iterator<String> iterator = type.keysIt();            while (iterator.hasNext()) {                MappingMetaData mappingMetaData = type.get(iterator.next());                System.out.println(JSON.toJSON(mappingMetaData.getSourceAsMap()));            }        }    }}

测试结果:

truetruetrue["index_test",".monitoring-es-2-2017.03.29",".monitoring-es-2-2017.03.28",".monitoring-data-2",".monitoring-es-2-2017.03.27","twitter",".monitoring-es-2-2017.03.30","test1"]true{"properties":{"userId":{"type":"keyword"}}}
0 0
原创粉丝点击