EsClient.java 2.78 KB
package com.cjs.cms.util.elasticsearch;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import com.cjs.cms.util.file.ReadResourceUtils;

/**
 * ElasticSearch Client
 * 
 * @author tongyufu
 *
 */

public class EsClient {

    public static final String                  INDEX       = "cjs";
    public static final String                  TYPE        = "entrust";
    private static String                       clusterName = "elasticsearch";
    private static Map<String, TransportClient> clientMap   = new HashMap<String, TransportClient>();

    static {
        Settings.Builder builder = Settings.builder();
        builder.put("cluster.name", clusterName);
        builder.put("client.transport.sniff", true);
        try {
            Properties props = ReadResourceUtils.getPropertyFile("/config.properties");
            String host = props.getProperty("es.host");
            String port = props.getProperty("es.port");
            InetSocketTransportAddress[] transportAddress = new InetSocketTransportAddress[1];
            transportAddress[0] = new InetSocketTransportAddress(InetAddress.getByName(host),
                Integer.valueOf(port));
            addClient(builder.build(), transportAddress);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    private EsClient() {
    }

    public static TransportClient getClient() {
        return EsClient.getClient(clusterName);
    }

    public static TransportClient getClient(String clusterName) {
        return EsClient.clientMap.get(clusterName);
    }

    @SuppressWarnings("unchecked")
    public static void addClient(Settings settings, InetSocketTransportAddress[] transportAddress) {
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddresses(transportAddress);
        clientMap.put(settings.get("cluster.name"), client);
    }

    /**
     * 高亮关键字
     * 
     * @param field 字段
     */
    public static HighlightBuilder highlight(String field) {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<span style='color: #d63239;'>"); //设置前缀
        highlightBuilder.postTags("</span>"); //设置后缀
        highlightBuilder.field(field); //设置高亮字段
        return highlightBuilder;
    }
}