EsClient.java
2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.cjs.site.biz.ec;
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.site.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 env = props.getProperty("env", "dev") + ".";
String host = props.getProperty(env + "es.host");
String port = props.getProperty(env + "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;
}
}