1.創建maven項目
編輯器:IDEA
創建項目完成後,將maven配置到自己安裝的位置,並將setting文件和repository配置好。
2.pom文件依賴
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
3.javaAPI操作
package com.dengdan.es;
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.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class ESTest {
/**
* 客戶端
*/
private PreBuiltTransportClient client = null;
/**
* 獲取客戶端
*
* @return
* @throws UnknownHostException
*/
@Before
public void getClient() throws UnknownHostException {
//獲取集羣信息
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
//獲取客戶端
client = new PreBuiltTransportClient(settings);
//連接到具體的主機
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("master"), 9300));
System.out.println(client.toString());
}
/**
* 創建索引
*/
@Test
public void createIndex() {
//執行創建索引操作
client.admin().indices().prepareCreate("blog4").get();
client.close();
}
/**
* 刪除索引
*/
@Test
public void delIndex() {
//執行刪除索引的操作
client.admin().indices().prepareDelete("blog").get();
//關閉客戶端
client.close();
}
/**
* 插入數據 以json格式
*/
@Test
public void createDocumentByJson() {
// 1 文檔數據準備
String json = "{" + "\"id\":\"1\"," + "\"title\":\"基於Lucene的搜索服務器\","
+ "\"content\":\"它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口\"" + "}";
// 2 創建文檔
IndexResponse response = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();
//3.打印返回信息
System.out.println(response.getIndex());
System.out.println(response.getType());
System.out.println(response.getResult());
System.out.println(response.getId());
//4.關閉客戶端
client.close();
}
/**
* 插入數據 以map格式
*/
@Test
public void createDocumentByMap() {
// 1 文檔數據準備
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", "2");
map.put("title", "基於Lucene的搜索服務器");
map.put("content", "它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口");
// 2 創建文檔
IndexResponse response = client.prepareIndex("blog", "article", "2").setSource(map).execute().actionGet();
//3.打印返回信息
System.out.println(response.getIndex());
System.out.println(response.getType());
System.out.println(response.getResult());
System.out.println(response.getId());
//4.關閉客戶端
client.close();
}
/**
* 插入文檔 以ES 構建器
*/
@Test
public void createDocumentByES() throws IOException {
//1.通過es自帶的幫助類,構建json數據
XContentBuilder data = XContentFactory.jsonBuilder().startObject()
.field("id", 4)
.field("title", "虎哥")
.field("content", "喫飯睡覺打豆豆")
.endObject();
// 2 創建文檔
IndexResponse response = client.prepareIndex("blog", "article", "3").setSource(data).execute().actionGet();
//3.打印返回信息
System.out.println(response.getIndex());
System.out.println(response.getType());
System.out.println(response.getResult());
System.out.println(response.getId());
//4.關閉客戶端
client.close();
}
/**
* 搜索文檔數據
*/
@Test
public void getData() {
//1.獲取數據
GetResponse response = client.prepareGet("blog", "article", "1").get();
//2.打印數據
System.out.println(response.getSourceAsString());
//3.關閉連接
client.close();
}
/**
* 搜索多條文檔數據
*/
@Test
public void getMultiData() {
//1.獲取多條文檔數據
MultiGetResponse itemResponses = client.prepareMultiGet().add("blog", "article", "1")
.add("blog", "article", "1", "2", "3")
.add("blog", "article", "2")
.get();
//2.打印數據
for (MultiGetItemResponse response : itemResponses) {
GetResponse response1 = response.getResponse();
if (response1.isExists()) {
//打印每一條數據
System.out.println(response1.getSourceAsString());
}
}
//3.關閉客戶端
client.close();
}
/**
* 更新文檔數據
*/
@Test
public void update() throws IOException, ExecutionException, InterruptedException {
//1.獲取更新請求
UpdateRequest request = new UpdateRequest("blog", "article", "3")
.doc(XContentFactory.jsonBuilder().startObject()
.field("id", "3")
.field("title", "班長")
.field("content", "班長喫飯睡覺打豆豆")
.endObject());
//2.執行更新操作
client.update(request).get();
//3.關閉客戶端
client.close();
}
/**
* 更新數據,找不到就插入數據
*/
@Test
public void upsert() throws IOException, ExecutionException, InterruptedException {
//1.獲取插入請求
IndexRequest indexRequest = new IndexRequest("blog", "article", "5")
.source(XContentFactory.jsonBuilder().startObject()
.field("id", "3")
.field("title", "舒總")
.field("content", "班長喫飯睡覺打豆豆")
.endObject());
//2.獲取更新請求
UpdateRequest request = new UpdateRequest("blog", "article", "5")
.doc(XContentFactory.jsonBuilder().startObject()
.field("id", "3")
.field("title", "班長")
.field("content", "班長喫飯睡覺打豆豆,撩妹")
.endObject()).upsert(indexRequest);
//3.執行更新操作
client.update(request).get();
//4.關閉客戶端
client.close();
}
/**
* 刪除文檔數據
*/
@Test
public void delete() {
//執行刪除操作
DeleteResponse deleteResponse = client.prepareDelete("blog", "article", "5").get();
//關閉客戶端
client.close();
}
/**
* 查詢所有數據
*/
@Test
public void matchAll() {
//1.執行相關查詢
SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
QueryBuilders.matchAllQuery()).get();
SearchHits hits = response.getHits();
//2.打印出命中多少文檔數據
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
//3.打印出實際數據
System.out.println(sourceAsString);
}
//4.關閉客戶端
client.close();
}
/**
* 分詞查詢
*/
@Test
public void query() {
//1.執行相關查詢
SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
QueryBuilders.queryStringQuery("分佈式")).get();
SearchHits hits = response.getHits();
//2.打印出命中多少文檔數據
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
//3.打印出實際數據
System.out.println(sourceAsString);
}
//4.關閉客戶端
client.close();
}
/**
* 通配符查詢
*/
@Test
public void wildCard() {
//1.執行相關查詢
SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
QueryBuilders.wildcardQuery("content", "*分")).get();
SearchHits hits = response.getHits();
//2.打印出命中多少文檔數據
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
//3.打印出實際數據
System.out.println(sourceAsString);
}
//4.關閉客戶端
client.close();
}
/**
* 詞條查詢
*/
@Test
public void termQuery() {
//1.執行相關查詢
SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
QueryBuilders.termQuery("content", "分佈式")).get();
SearchHits hits = response.getHits();
//2.打印出命中多少文檔數據
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
//3.打印出實際數據
System.out.println(sourceAsString);
}
//4.關閉客戶端
client.close();
}
/**
* 模糊查詢
*/
@Test
public void fuzzy() {
//1.執行相關查詢
SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(
QueryBuilders.fuzzyQuery("title", "lucen")).get();
SearchHits hits = response.getHits();
//2.打印出命中多少文檔數據
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
//3.打印出實際數據
System.out.println(sourceAsString);
}
//4.關閉客戶端
client.close();
}
/**
* 映射操作
*
* @throws Exception
*/
@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")
.endObject()
.startObject("title2")
.field("type", "string")
.field("store", "no")
.endObject()
.startObject("content")
.field("type", "string")
.field("store", "yes")
.endObject()
.endObject()
.endObject()
.endObject();
// 2 添加mapping
PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);
client.admin().indices().putMapping(mapping).get();
// 3 關閉資源
client.close();
}
}