创建索引:
public static void inits() throws IOException, InterruptedException, ExecutionException {
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
client.admin().indices().prepareCreate("book").execute().actionGet();
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("title").field("type", "string").field("store", "yes").endObject()
.startObject("year").field("type", "integer").field("store", "yes").endObject()
.startObject("content").field("type", "text").field("store", "yes").field("analyzer", "ik_max_word").field("search_analyzer","ik_max_word").endObject()
.endObject()
.endObject()
.endObject();
PutMappingRequest mapping = Requests.putMappingRequest("book").type("article").source(builder);
client.admin().indices().putMapping(mapping).actionGet();
}
添加数据:
public static void add() throws IOException, InterruptedException, ExecutionException {
String json = "{\"title\":\"国歌\", \"year\":1885,\"content\":\"起来不愿做奴隶的人民,把我们的血肉筑成我们新的长城北上广南京天安门,中华民族到了最危险的时候,每个人们都。。。。\"}";
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
IndexResponse indexResponse = client
.prepareIndex("book", "article", "1")
.setSource(json, XContentType.JSON)
.execute().get();
}
查询数据:
@Test
public static void searchAll() throws UnknownHostException {
try {
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
QueryBuilder queryBuilder = QueryBuilders.matchQuery("content", "天安门长城").analyzer("ik_max_word").operator(Operator.AND);
HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);;
highlightBuilder.preTags("<span style=\"color:red\">");
highlightBuilder.postTags("</span>");
SearchResponse searchResponse = client.prepareSearch("book").setTypes("article").highlighter(highlightBuilder).setQuery(queryBuilder).execute().actionGet();
SearchHit[] hits = searchResponse.getHits().getHits();
System.out.println(hits.length);
for (SearchHit hit : hits) {
Map<String, HighlightField> result = hit.getHighlightFields();
//从设定的高亮域中取得指定域
HighlightField titleField = result.get("content");
//取得定义的高亮标签
Text[] titleTexts = titleField.fragments();
//为title串值增加自定义的高亮标签
String title = "";
for(Text text : titleTexts){
title += text;
}
System.out.println(title);
}
} catch(UnknownHostException e) {
e.printStackTrace();
}
}