1、Code -> GitHub
https://github.com/liufengji/elasticsearch_api.git
2、创建索引
//创建索引(数据库)
@Test
public void createIndex() {
//创建索引
client.admin().indices().prepareCreate("blog4").get();
//关闭资源
client.close();
}
3、创建mapping
//创建使用ik分词器的mapping
@Test
public void createMapping() throws Exception {
// 1设置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 关闭资源
client.close();
}
4、插入数据
//创建文档,以map形式
@Test
public void createDocumentByMap() {
HashMap<String, String> map = new HashMap<>();
map.put("id1", "2");
map.put("title2", "Lucene");
map.put("content", "它提供了一个分布式的web接口");
IndexResponse response = client.prepareIndex("blog4", "article", "3")
.setSource(map).execute().actionGet();
//打印返回的结果
System.out.println("结果:" + 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());
//关闭资源
client.close();
}
5、词条查询
//词条查询
@Test
public void queryTerm() {
SearchResponse response = client.prepareSearch("blog4").setTypes("article")
.setQuery(QueryBuilders.termQuery("content","提供")).get();
//获取查询命中结果
SearchHits hits = response.getHits();
System.out.println("结果条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}