1.添加pom.xml依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.0</version>
</dependency>
API基本操作
2.連接到elasticsearch集群
private static TransportClient client;
static {// 1、獲取客戶端對象,設置連接的集群名稱
Settings settings= Settings.builder().put("cluster.name","elasticsearch").build();
client=new PreBuiltTransportClient(settings);
// 2、連接集群
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop-001"), 9300));
System.out.println(client.toString());
} catch (UnknownHostException e) {
e.printStackTrace();
}}
3.創建索引
public static void creatIndex(){
//1.創建索引(indices指數)
client.admin().indices().prepareCreate("blog").get();
//2.關閉連接
client.close();
}
4.刪除索引
public static void deleteIndex(){
//1.創建索引(indices指數)
client.admin().indices().prepareDelete("blog").get();
//2.關閉連接
client.close();
}
5 新建文檔(源數據是手寫的 json 串)
public static void creatIndexByJason(){
// 1、文檔數據准備
String json = "{" + "\"id\":\"1\"," + "\"title\":\"基於Lucene的搜索服務器\","
+ "\"content\":\"它提供了一個分布式多用戶能力的全文搜索引擎,基於RESTful web接口\"" + "}";
String jason2="{"+ "\"id\":\"1\","+"\"title\":\"基於Lucene的搜索服務器\","
+"\"content\":\"它提供了一個分布式多用戶的全文搜索引擎,基於RESTful web接口\""+"}";
//2.創建文檔
IndexResponse indexResponse=client.prepareIndex("blog","article","1").setSource(json).execute().actionGet();
// 3、打印返回的結果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 4、關閉連接
client.close();
}
6 新建文檔(源數據是以 map 方式添加的鍵值對)
public static void creatIndexByMap(){
// 1、文檔數據准備
Map<String,Object> json=new HashMap<String,Object>(); //2.創建文檔
json.put("id", "2");
json.put("title", "基於Lucene的搜索服務器");
json.put("content", "它提供了一個分布式多用戶能力的全文搜索引擎,基於RESTful web接口");
IndexResponse indexResponse=client.prepareIndex("blog","article","2").setSource(json).execute().actionGet();
// 3、打印返回的結果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 4、關閉連接
client.close();
}
7 新建文檔(源數據是通過 es 構建器構建的數據)
public static void creatIndexByBuilder() {
//1.通過es自帶的幫助類,來構建json數據
XContentBuilder builder= null;
try {
builder = XContentFactory.jsonBuilder().startObject()
.field("id","3")
.field("title","基於Lucene的搜索服務器")
.field("content", "它提供了一個分布式多用戶能力的全文搜索引擎,基於RESTful web接口")
.endObject();
} catch (IOException e) {
e.printStackTrace();
}
IndexResponse indexResponse=client.prepareIndex("blog","article","3").setSource(builder).execute().actionGet();
// 3、打印返回的結果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 4、關閉連接
client.close();
}
8 搜索文檔數據(單個索引)
public static void getData() {
// 1、查詢文檔
GetResponse response = client.prepareGet("blog", "article", "1").get();
// 2、打印搜索的結果
System.out.println(response.getSourceAsString());
// 3、關閉連接
client.close();
}
9 搜索文檔數據(多個索引)
public static void getMultiData() {
// 1、查詢多個文檔
MultiGetResponse response = client.prepareMultiGet()
.add("blog", "article", "1")
.add("blog", "article", "2", "3")
.add("blog", "article", "2").get();
// 2、遍歷返回的結果
for (MultiGetItemResponse itemResponse : response) {
GetResponse getResponse = itemResponse.getResponse();
// 如果獲取到查詢結果
if (getResponse.isExists()) {
String sourceAsString = getResponse.getSourceAsString();
System.out.println(sourceAsString);
}
}
// 3、關閉資源
client.close();
}
10 更新文檔數據(update)
public static void updateData() {
// 1、創建更新數據的請求對象
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("blog");
updateRequest.type("article");
updateRequest.id("3");
try {
updateRequest.doc(XContentFactory.jsonBuilder().startObject()
.field("title", "基於Lucene的搜索服務器") // 對沒有的字段進行添加,對已有的字段進行替換
.field("content", "它提供了一個分布式多用戶能力的全文搜索引擎,基於RESTful web接口。大數據前景無限")
.field("createDate", "2017-8-22").endObject());
} catch (IOException e) {
e.printStackTrace();
}
// 2、獲取更新后的值
UpdateResponse indexResponse = null;
try {
indexResponse = client.update(updateRequest).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// 3、打印返回的結果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 4、關閉連接
client.close();
}
11 更新文檔數據(upsert)
public static void upsertData() throws Exception {
// 設置查詢條件,查找不到則添加 IndexRequest 內容
IndexRequest indexRequest = new IndexRequest("blog", "article", "5")
.source(XContentFactory.jsonBuilder().startObject()
.field("title", "搜索服務器")
.field("content","Elasticsearch是用Java開發的,並作為Apache許可條款下的開放源碼發布,是當前流行的企業級搜索引擎。").endObject());
// 設置更新,查找到則按照 UpdateRequest 更新
UpdateRequest upsert = new UpdateRequest("blog", "article", "5")
.doc(XContentFactory.jsonBuilder().startObject().field("user", "李四").endObject()).upsert(indexRequest);
client.update(upsert).get();
client.close();
}
12 刪除文檔數據(prepareDelete)
public static void deleteData() {
// 1、刪除文檔數據
DeleteResponse indexResponse = client.prepareDelete("blog", "article", "2").get();
// 2、打印返回的結果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 3、關閉連接
client.close();
}
條件查詢
1 查詢所有(matchAllQuery)
public static void matchAllQuery(){
//1.執行查詢(查詢所有)
SearchResponse searchResponse=client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.matchAllQuery()).get();
// 2、打印查詢結果
SearchHits hits=searchResponse.getHits();//獲取命中數,查詢結果有多少對象
System.out.println("查詢結果一共有"+hits.totalHits+"條");
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
2 對所有字段分詞查詢(queryStringQuery)
public static void queryStringQuery() {
// 1、條件查詢(對所有字段分詞查詢)
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.queryStringQuery("全文")).get();
// 2、打印查詢結果
SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
System.out.println("查詢結果有:" + hits.getTotalHits() + "條");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
SearchHit searchHit = iterator.next(); // 每個查詢對象
System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
}
// 3、關閉連接
client.close();
}
3 通配符查詢(wildcardQuery)
public static void wildcardQuery() {
// 1、通配符查詢
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();
// 2、打印查詢結果
SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
System.out.println("查詢結果有:" + hits.getTotalHits() + "條");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
SearchHit searchHit = iterator.next(); // 每個查詢對象
System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
}
// 3、關閉連接
client.close();
}
4 詞條查詢(TermQuery)
public static void termQuery() {
// 1、詞條查詢
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.termQuery("content", "全")).get(); // 因為沒有使用 IK 分詞器,所有只能一個字一個字的查
// 2、打印查詢結果
SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
System.out.println("查詢結果有:" + hits.getTotalHits() + "條");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
SearchHit searchHit = iterator.next(); // 每個查詢對象
System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
}
// 3、關閉連接
client.close();
}
5 模糊查詢(fuzzy)
public static void fuzzyQuery() {
// 1、模糊查詢
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.fuzzyQuery("title", "lucene")).get();
// 2、打印查詢結果
SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
System.out.println("查詢結果有:" + hits.getTotalHits() + "條");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
SearchHit searchHit = iterator.next(); // 每個查詢對象
System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
}
// 3、關閉連接
client.close();
}
映射相關操作
public static void createMapping() throws Exception {
// 1、創建索引(indices 指數)
//client.admin().indices().prepareCreate("blog2").get();
// 1、設置 mapping
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article2")
.startObject("properties")
.startObject("id2")
.field("type", "text")
.field("store", "true")
.endObject()
.startObject("title2")
.field("type", "text")
.field("store", "false")
.endObject()
.startObject("content2")
.field("type", "text")
.field("store", "true")
.endObject()
.endObject()
.endObject()
.endObject();
// 2、添加 mapping
PutMappingRequest mapping = Requests.putMappingRequest("blog2").type("article2").source(builder);
client.admin().indices().putMapping(mapping).get();
// 3、關閉資源
client.close();
}