@Test public void testESCreateIndex() throws IOException, InterruptedException { String esRoot = "http://localhost:9200/stations";//index地址 String result = restTemplate.getForObject(esRoot, String.class, ""); System.out.println(result); restTemplate.delete(esRoot); HttpEntity<String> formEntity = new HttpEntity<String>(IOUtil.loadData2String(AppTest.class.getResource("/mapper.json").getPath()), new HttpHeaders()); restTemplate.put(esRoot, formEntity); }
mapping.json
{ "mappings": { "station": { "properties": { "company": { "type": "text", "analyzer": "lc_index", "search_analyzer": "lc_search", "term_vector": "with_positions_offsets" }, "address": { "type": "text", "analyzer": "lc_index", "search_analyzer": "lc_search", "term_vector": "with_positions_offsets" }, "areaName": { "type": "text", "analyzer": "lc_index", "search_analyzer": "lc_search", "term_vector": "with_positions_offsets" }, "loc": { "type": "geo_point" } } } } }
@Test public void testESSearch() throws UnknownHostException { TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); String[] searchFieldNames = {"company", "address"}; QueryBuilder qb = boolQuery().must(multiMatchQuery("江苏 鼓楼", searchFieldNames).type(PHRASE).analyzer("lc_index")); SearchRequestBuilder req = client.prepareSearch(INDEX) .setTypes(TYPE).setExplain(true) .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.DESC) .setQuery(qb) .setFetchSource(searchFieldNames,null) .setFrom(0).setSize(100); /** *查看搜索json串 */ System.out.println(req.toString()); SearchResponse response = req.get(); if (response.getHits().getHits().length > 0) { for (SearchHit hit : response.getHits().getHits()) { for (int i = 0; i < searchFieldNames.length; i++) { System.out.print("| "+hit.getSourceAsMap().get(searchFieldNames[i]) ); } System.out.println(); } } // on shutdown client.close(); }