elasticsearch 搜索续

elasticsearch工具类

环境 jdk1.7 playframework 1.3.0

1
2
3
4
5
6
package utils;

public class Order {
public String id; //id
public String trade_no; //业务单号
}
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
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.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;


public class EsUtil {

private Client client;
private String INDEX_NAME = "testproject";
private String ORDER_TYPE = "orders";
private String CLUSTER_NAME = "cluster.name";
private static EsUtil esutil = null;

private EsUtil() {
try {
Settings settings = Settings.settingsBuilder()
.put(CLUSTER_NAME, "elasticsearch")
.build();
String host = "localhost";
Integer port = 9300;
client = TransportClient
.builder()
.settings(settings)
.build()
.addTransportAddress(
new InetSocketTransportAddress(InetAddress
.getByName(host), port));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}

public static EsUtil getEsUtil() {
if (esutil==null) {
esutil=new EsUtil();
}
//esutil.refresh();
return esutil;
}

/**
* @param id 订单ID
* @param trade_no 系统编号
*/

public void createOrderIndex(Order order) {
XContentBuilder sourceBuilder = getSourceBuilder(order);
if(sourceBuilder != null) upsertIndex(INDEX_NAME, ORDER_TYPE, order.id, sourceBuilder);
}

public long getCount(String index,String type,BoolQueryBuilder tqb) {
long counts=0;
try {
SearchResponse response = client.prepareSearch(index)
// 设置查询索引类型,setTypes("productType1", "productType2","productType3");
// 可用来设定在多个类型中搜索
.setTypes(type)
//设置查询类型 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询 2.SearchType.SCAN =扫描查询,无序
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//设置查询关键词
.setQuery(tqb)
//设置是否按查询匹配度排序
.setExplain(true)
//执行搜索,返回搜索响应信息
.execute().actionGet();
SearchHits hits = response.getHits();
if (null != hits && hits.totalHits() > 0) {
counts= hits.totalHits();
}
} catch (Exception e) {
e.printStackTrace();
return counts;
}
return counts;
}

public List<Order> search(String index,String type,BoolQueryBuilder tqb,int page) {
List<Order> list=new ArrayList<>();
try {
SearchResponse response = client.prepareSearch(index)
// 设置查询索引类型,setTypes("productType1", "productType2","productType3");
// 可用来设定在多个类型中搜索
.setTypes(type)
//设置查询类型 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询 2.SearchType.SCAN =扫描查询,无序
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//设置查询关键词
.setQuery(tqb)
.addSort("id", SortOrder.DESC)
//分页
.setFrom((page-1)*10).setSize(10)
//设置是否按查询匹配度排序
// .setExplain(true)
//执行搜索,返回搜索响应信息
.execute().actionGet();
SearchHits hits = response.getHits();
// System.out.println(hits.totalHits());
if (null != hits && hits.totalHits() > 0) {
for (SearchHit hit : hits) {
//将文档中的每一个对象转换json串值
String json = hit.getSourceAsString();
System.out.println(json);
// Gson gson = new Gson();
// //将json串值转换成对应的实体对象
// OrderIndex order=gson.fromJson(json, OrderIndex.class);
// Order orderx=Order.findById(order.id);
// list.add(orderx);
}
} else {
System.out.println("没有查询到任何结果!");
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

private XContentBuilder getSourceBuilder(Order order){
try {
XContentBuilder sourceBuilder = XContentFactory.jsonBuilder().startObject()
.field("trade_no", order.trade_no)
.field("id",order.id)
.endObject();
return sourceBuilder;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

private void upsertIndex(String index,String type,String id,XContentBuilder sourceBuilder) {
try {
IndexRequest indexRequest = new IndexRequest(index,type,id).source(sourceBuilder);
UpdateRequest updateRequest = new UpdateRequest(index,type,id).doc(sourceBuilder).upsert(indexRequest);
UpdateResponse response = client.update(updateRequest).get();
System.out.println("是否新增:" + response.isCreated());
System.out.println(response);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}

public void isExist(Order order) {
GetResponse getResponse = client.prepareGet(INDEX_NAME, ORDER_TYPE, order.id).get();
System.out.println(getResponse.getSourceAsString());
System.out.println("getResponse:"+getResponse.isExists());
}


public void deleteIndex(){
//删除指定索引
if (isIndexExist()) {
client.admin().indices().prepareDelete(INDEX_NAME).execute().actionGet();
}
}

public boolean isIndexExist(){
IndicesExistsResponse getResponse =client.admin().indices().prepareExists(INDEX_NAME).execute().actionGet();
return getResponse.isExists();
}


//初始化订单索引
public void initOrderIndex(){
//批量添加订单的索引
List<Order> list=new ArrayList<>();
Order obj =new Order();
obj.id="10001";
obj.trade_no="dn00001";
list.add(obj);
try {
for (Order order : list) {
createOrderIndex(order);
}
} catch (Exception e) {
e.printStackTrace();
}

}

public void close() {
// client.close();
}
public void refresh() {
client.admin().indices().prepareRefresh(INDEX_NAME).get();
}

public static void main(String[] args) {
//初始化生成订单索引
EsUtil eu3 = EsUtil.getEsUtil();
eu3.initOrderIndex();
eu3.close();
}


}