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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
| import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.controller.DateUtils; import org.elasticsearch.action.admin.indices.analyze.AnalyzeAction; import org.elasticsearch.action.admin.indices.analyze.AnalyzeRequestBuilder; import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateResponse; 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.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.*; import org.elasticsearch.search.SearchHits; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
public class ElasticsearchTest {
private Logger logger = LoggerFactory.getLogger(ElasticsearchTest.class);
public final static String HOST = "10.10.13.234";
public final static int PORT = 9300;
Client client; private static String index = "my_index"; private static String type = "skuId"; private static String clusterName = "my-application";
@Test public void createMapping()throws Exception { String indices = "jd_mall_v2"; String mappingType = "goods";
Settings settings = Settings.settingsBuilder() .put("cluster.name", clusterName) .put("client.transport.sniff", true) .build();
Client client = TransportClient.builder().settings(settings).build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
client.admin().indices().prepareCreate(indices).execute().actionGet(); new XContentFactory(); XContentBuilder builder=XContentFactory.jsonBuilder() .startObject() .startObject(mappingType) .startObject("properties") .startObject("name").field("type", "string").field("store", "yes").field("analyzer","ik").field("index","analyzed").endObject() .startObject("price").field("type", "long").endObject() .endObject() .endObject() .endObject(); PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
client.admin().indices().putMapping(mapping).actionGet(); client.close(); }
@Before public void before() {
Settings settings = Settings.settingsBuilder() .put("cluster.name", clusterName) .put("client.transport.sniff", true) .build();
try { client = TransportClient.builder().settings(settings).build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT)); System.out.println("Elasticsearch connect info:" + client.toString()); } catch (UnknownHostException e) { e.printStackTrace(); }
}
@SuppressWarnings("resource") @Test public void test1() throws UnknownHostException {
TransportClient client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
logger.debug("Elasticsearch connect info:" + client.toString()); System.out.println("Elasticsearch connect info:" + client.toString());
client.close(); }
@Test public void testGet() throws Exception {
String skuId = "3724941"; String skuName = "华盛顿苹果礼盒 8个装(4个红蛇果+4个青苹果)单果重约145g-180g 新鲜水果礼盒"; String skuPrice = "4990";
List<String> listAnalysis = getIkAnalyzeSearchTerms("进口水果");
List<Map<String, Object>> resultList3 = testQueryStringQuery(index, type, "name", "进口水果");
}
@Test public void testCreate() throws Exception { String[] skuIds = {"2246904", "2138027", "3724941", "5664705", "3711635"}; String[] skuNames = {"果花 珍珠岩 无土栽培基质 颗粒状 保温性能好 园艺用品", "进口华盛顿红蛇果 苹果4个装 单果重约180g 新鲜水果", "华盛顿苹果礼盒 8个装(4个红蛇果+4个青苹果)单果重约145g-180g 新鲜水果礼盒", "新疆阿克苏冰糖心 约5kg 单果200-250g(7Fresh 专供)", "江西名牌 杨氏精品脐橙 5kg装 铂金果 水果橙子礼盒 2种包装随机发货"}; String[] skuPrices = {"500", "3800", "4990", "8500", "5880"};
for (int i=0; i<skuIds.length; i++) { String skuId = skuIds[i]; String skuName = skuNames[i]; String skuPrice = skuPrices[i];
String jsonStr = "{" + "\"skuId\":\""+skuId+"\"," + "\"skuName\":\""+skuName+"\"," + "\"skuPrice\":\""+skuPrice+"\"" + "}";
IndexResponse response = client.prepareIndex(index, type, skuId) .setSource(jsonStr,XContentType.JSON) .get(); boolean created = response.isCreated(); System.out.println("创建一条记录:" + created);
GetResponse response1 = client.prepareGet(index, type, skuId).get(); response1.getSourceAsMap(); System.out.println("查询一条数据:" + JSON.toJSON(response1.getSourceAsMap())); } }
@Test public void testDelete() throws Exception { String skuId = "3724941"; String skuName = "华盛顿苹果礼盒 8个装(4个红蛇果+4个青苹果)单果重约145g-180g 新鲜水果礼盒"; String skuPrice = "4990"; String skuImage = "jfs/t16450/249/461724533/219792/7f204d7a/5a321ecbN4526f7d3.jpg";
DeleteResponse response2 = client.prepareDelete(index, type, skuId).get(); System.out.println("删除一条数据:" + response2.isFound());
GetResponse response1 = client.prepareGet(index, type, skuId).get(); response1.getSourceAsMap(); System.out.println("查询一条数据:" + JSON.toJSON(response1.getSourceAsMap())); }
@Test public void testUpdate() throws Exception { String skuId = "3724941"; String skuName = "华盛顿苹果礼盒 8个装(4个红蛇果+4个青苹果)单果重约145g-180g 新鲜水果礼盒"; String skuPrice = "4990"; String skuName2 = "华圣 陕西精品红富士苹果 12个装 果径75mm 约2.1kg 新鲜水果"; UpdateResponse updateResponse = client.prepareUpdate(index, type, skuId).setDoc(jsonBuilder() .startObject() .field("name", skuName2) .endObject()) .get(); System.out.println("更新一条数据:" + updateResponse.isCreated());
GetResponse response1 = client.prepareGet(index, type, skuId).get(); response1.getSourceAsMap(); System.out.println("查询一条数据:" + JSON.toJSON(response1.getSourceAsMap())); }
public byte[] convertByteArray(Object obj) { ObjectMapper mapper = new ObjectMapper(); try { byte[] json = mapper.writeValueAsBytes(obj); return json; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; }
public String jsonStr(Object obj) { return JSON.toJSONString(obj); }
public List getQueryDataBySingleField(String index, String type, String key, String value){ QueryBuilder qb = QueryBuilders.termQuery(key, value); SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(qb) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); }
public List getBoolDataByMuchField(String index, String type, Map<String,String> map){ BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); for (String in : map.keySet()) { String str = map.get(in); boolQueryBuilder.must(QueryBuilders.termQuery(in,str)); } SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(boolQueryBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); }
public List getDataByWildcard(String index, String type, String key, String value){ WildcardQueryBuilder wBuilder = QueryBuilders.wildcardQuery(key, value); SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(wBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); }
public List getDataByMuchWildcard(String index, String type, Map<String,String> map){ BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); for (String in : map.keySet()) { String str = map.get(in); boolQueryBuilder.must(QueryBuilders.wildcardQuery(in,str)); } SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(boolQueryBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet();
return responseToList(client,response); }
public List getDataByMatch(String index, String type, String key, String value){ MatchQueryBuilder mBuilder = QueryBuilders.matchQuery(key, value); SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(mBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); }
public List getDataByPrefix(String index, String type, String key, String value){ PrefixQueryBuilder pBuilder = QueryBuilders.prefixQuery(key, value); SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(pBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); }
public List testSearchByPrefix(String index, String key, String value) { SearchResponse response = client.prepareSearch(index) .setSearchType(SearchType.DEFAULT)
.setQuery(QueryBuilders.prefixQuery(key, value)) .get(); return responseToList(client,response); }
public List testFuzzyQuery(String index, String type, String key, String value){ FuzzyQueryBuilder fBuilder = QueryBuilders.fuzzyQuery(key, value); SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(fBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); } public List testQueryStringQuery(String index, String type, String key, String value){ QueryBuilder fBuilder = QueryBuilders.queryStringQuery(value).field(key); SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(fBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); } public List testMultiQueryStringQuery(String index, String type, String key, List<String> listAnalysis){ BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); for (String term : listAnalysis) { boolQueryBuilder.should(QueryBuilders.queryStringQuery(term).field(key)); } SearchResponse response = client.prepareSearch(index).setTypes(type) .setQuery(boolQueryBuilder) .setFrom(0).setSize(10000).setExplain(true) .execute() .actionGet(); return responseToList(client,response); }
public List responseToList(Client client, SearchResponse response){ SearchHits hits = response.getHits(); List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); System.out.println("------------------------"); for (int i = 0; i < hits.getHits().length; i++) { Map<String, Object> map = hits.getAt(i).getSource(); System.out.println(map.get("name")); list.add(map); } System.out.println("------------------------"); return list; }
private List<String> getIkAnalyzeSearchTerms(String searchContent) { AnalyzeRequestBuilder ikRequest = new AnalyzeRequestBuilder(client, AnalyzeAction.INSTANCE, index, searchContent); ikRequest.setTokenizer("ik"); List<AnalyzeResponse.AnalyzeToken> ikTokenList = ikRequest.execute().actionGet().getTokens();
List<String> searchTermList = new ArrayList<>(); for (AnalyzeResponse.AnalyzeToken ikToken: ikTokenList) { System.out.println(ikToken.getTerm()); searchTermList.add(ikToken.getTerm()); }
return searchTermList; }
@Test public void testFromSize() { System.out.println("from size 模式启动!"); long begin = System.currentTimeMillis(); long count = client.prepareCount(index).setTypes(type).execute() .actionGet().getCount(); SearchRequestBuilder requestBuilder = client.prepareSearch(index).setTypes(type) .setQuery(QueryBuilders.queryStringQuery("进口水果").field("name")); for (int i=0,sum=0; sum<count; i++) { SearchResponse response = requestBuilder.setFrom(i).setSize(3).execute().actionGet(); sum += response.getHits().hits().length; responseToList(client,response); System.out.println("总量"+count+", 已经查到"+sum); } System.out.println("elapsed<"+(System.currentTimeMillis()-begin)+">ms."); }
@Test public void testScroll() { System.out.println("scroll 模式启动!"); long begin = System.currentTimeMillis(); SearchResponse scrollResponse = client.prepareSearch(index) .setTypes(type) .setQuery(QueryBuilders.queryStringQuery("进口水果").field("name")) .setSearchType(SearchType.SCAN).setSize(3).setScroll(TimeValue.timeValueMinutes(1)) .execute().actionGet(); long count = scrollResponse.getHits().getTotalHits(); for (int i=0,sum=0; sum<count; i++) { scrollResponse = client.prepareSearchScroll(scrollResponse.getScrollId()) .setScroll(TimeValue.timeValueMinutes(8)).execute().actionGet(); sum += scrollResponse.getHits().hits().length; responseToList(client,scrollResponse); System.out.println("总量"+count+", 已经查到"+sum); } System.out.println("elapsed<"+(System.currentTimeMillis()-begin)+">ms."); } }
|