1絮供、Code -> GitHub
https://github.com/liufengji/elasticsearch_api.git
2、創(chuàng)建索引
//創(chuàng)建索引(數(shù)據(jù)庫(kù))
@Test
public void createIndex() {
//創(chuàng)建索引
client.admin().indices().prepareCreate("blog4").get();
//關(guān)閉資源
client.close();
}
3泥彤、創(chuàng)建mapping
//創(chuàng)建使用ik分詞器的mapping
@Test
public void createMapping() throws Exception {
// 1設(shè)置mapping
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id1")
.field("type", "string")
.field("store", "yes")
.field("analyzer","ik_smart")
.endObject()
.startObject("title2")
.field("type", "string")
.field("store", "no")
.field("analyzer","ik_smart")
.endObject()
.startObject("content")
.field("type", "string")
.field("store", "yes")
.field("analyzer","ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
// 2 添加mapping
PutMappingRequest mapping = Requests.putMappingRequest("blog4")
.type("article").source(builder);
client.admin().indices().putMapping(mapping).get();
// 3 關(guān)閉資源
client.close();
}
4琴拧、插入數(shù)據(jù)
//創(chuàng)建文檔,以map形式
@Test
public void createDocumentByMap() {
HashMap<String, String> map = new HashMap<>();
map.put("id1", "2");
map.put("title2", "Lucene");
map.put("content", "它提供了一個(gè)分布式的web接口");
IndexResponse response = client.prepareIndex("blog4", "article", "3")
.setSource(map).execute().actionGet();
//打印返回的結(jié)果
System.out.println("結(jié)果:" + response.getResult());
System.out.println("id:" + response.getId());
System.out.println("index:" + response.getIndex());
System.out.println("type:" + response.getType());
System.out.println("版本:" + response.getVersion());
//關(guān)閉資源
client.close();
}
5晰甚、詞條查詢
//詞條查詢
@Test
public void queryTerm() {
SearchResponse response = client.prepareSearch("blog4").setTypes("article")
.setQuery(QueryBuilders.termQuery("content","提供")).get();
//獲取查詢命中結(jié)果
SearchHits hits = response.getHits();
System.out.println("結(jié)果條數(shù):" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}