美文网首页elasticsearch程序员
Elasticsearch Java API测试

Elasticsearch Java API测试

作者: jacksu在简书 | 来源:发表于2016-05-12 22:42 被阅读1252次
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class ESHelper {        // 创建私有对象
    private static TransportClient client;

    static {
        try {
            int port = 9300;
            Map<String, String> m = new HashMap<String, String>();
            // 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中,
            Settings settings = Settings.settingsBuilder().put(m).put("cluster.name", "elasticsearch").put("client.transport.sniff", true).build();
            client = TransportClient.builder().settings(settings).build();
            String ip = "";
            InetAddress host = InetAddress.getLocalHost();
            client.addTransportAddress(new InetSocketTransportAddress(host, port));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 取得实例
    public static synchronized TransportClient getTransportClient() {
        return client;
    }

    /**
     * 创建一个索引
     *
     * @param indexName 索引名
     */
    public static void createIndex(String indexName) {
        try {
            boolean indexExists = client.admin().indices().prepareExists(indexName).execute().actionGet().isExists();
            if (indexExists) {
                client.admin().indices().prepareDelete(indexName).execute().actionGet();
            }
            CreateIndexResponse indexResponse = getTransportClient().admin().indices().prepareCreate(indexName).get();
            System.out.println(indexResponse.isAcknowledged());
// true表示创建成功       
        } catch (ElasticsearchException e) {
            e.printStackTrace();
        }
    }

    public static XContentBuilder createMapping(String indexName, String type) {
        XContentBuilder mapping = null;
        try {
            mapping = jsonBuilder()
                    .startObject()                    // 索引里面的字段
                    .startObject("properties")
                    .startObject("id")
                    .field("type", "long")
                    .field("store", "yes")
                    .field("index", "not_analyzed")
                    .field("include_in_all", "false")
                    .endObject()
                    .startObject("thumb").field("type", "string").field("store", "yes").field("index", "not_analyzed").field("include_in_all", "false").endObject().endObject().endObject();
            System.out.println(mapping.string());
            PutMappingRequest mappingRequest = Requests.putMappingRequest(indexName).source(mapping).type(type);
            client.admin().indices().putMapping(mappingRequest).actionGet();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mapping;
    }

    public static Integer addIndex(String indexName, String indexType) {
        Client esClient = getTransportClient();
        BulkRequestBuilder bulkRequest = esClient.prepareBulk();
        for (int i = 1; i < 5; i++) {
            try {
                bulkRequest.add(esClient.prepareIndex(indexName, indexType, "" + i)
                        .setSource(jsonBuilder().startObject().field("id", "" + i)
                                .field("thumb", "http://www.chepoo.com/imges/" + i + ".jpg")
                                .endObject()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            bulkRequest.add(esClient.prepareIndex(indexName, indexType, "" + 5)
                    .setSource(jsonBuilder()
                            .startObject()
                            .field("id", "" + 5)
                            .field("thumb", "http://www.chepoo.com/imges/" + 5 + ".png")
                            .endObject()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        bulkRequest.execute().actionGet();
        return bulkRequest.numberOfActions();
    }

    public static void get(String index, String type) {
        client.admin().indices().flush(new FlushRequest(index).force(true)).actionGet();
        SearchResponse response = client.prepareSearch(index).setTypes(type)                //查询图片为jpg或者png
                .setQuery(new QueryStringQueryBuilder("jpg|png").field("thumb"))
                .setFrom(0).setSize(60).setExplain(true).execute().actionGet();
        System.out.println(response);
    }
}

相关文章

网友评论

    本文标题:Elasticsearch Java API测试

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