三.Java API操作

Elasticsearch的Java客戶端非常強大;它可以建立一個嵌入式實例并在必要時運行管理任務。

運行一個Java應用程序和Elasticsearch時,有兩種操作模式可供使用。該應用程序可在Elasticsearch集群中扮演更加主動或更加被動的角色。在更加主動的情況下(稱為Node Client),應用程序實例將從集群接收請求,確定哪個節點應處理該請求,就像正常節點所做的一樣。(應用程序甚至可以托管索引和處理請求。)另一種模式稱為Transport Client,它將所有請求都轉發到另一個Elasticsearch節點,由后者來確定最終目標。

3.1 API基本操作

3.1.1 操作環境準備

1)創建maven工程

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.6.1</version>

</dependency>

<dependency>

<groupId>org.elasticsearch.client</groupId>

<artifactId>transport</artifactId>

<version>5.6.1</version>

</dependency>

<dependency>

<groupId>org.apache.logging.log4j</groupId>

<artifactId>log4j-core</artifactId>

<version>2.9.0</version>

</dependency>

</dependencies>

3)等待依賴的jar包下載完成

當直接在ElasticSearch 建立文檔對象時,如果索引不存在的,默認會自動創建,映射采用默認方式

3.1.2 獲取Transport Client

(1)ElasticSearch服務默認端口9300。

(2)Web管理平臺端口9200。

private TransportClient client;

@SuppressWarnings("unchecked")

@Before

public void getClient() throws Exception {

// 1 設置連接的集群名稱

Settings settings = Settings.builder().put("cluster.name", "my-

application").build();

// 2 連接集群

client = new PreBuiltTransportClient(settings);

client.addTransportAddress(new

InetSocketTransportAddress(InetAddress.getByName("hadoop102"), 9300));

// 3 打印集群名稱

System.out.println(client.toString());

}

(3)顯示log4j2報錯,在resource目錄下創建一個文件命名為log4j2.xml并添加如下內容

<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="warn">

<Appenders>

<Console name="Console" target="SYSTEM_OUT">

<PatternLayout pattern="%m%n"/>

</Console>

</Appenders>

<Loggers>

<Root level="INFO">

<AppenderRef ref="Console"/>

</Root>

</Loggers>

</Configuration>

3.1.3 創建索引

1)源代碼

@Test

public void createIndex_blog(){

// 1 創建索引

client.admin().indices().prepareCreate("blog2").get();

// 2 關閉連接

client.close();

}

2)查看結果

{"blog2":{"aliases":{},"mappings":{},"settings":{"index":

{"creation_date":"1507466730030","number_of_shards":"5","number_of_replicas":"1"

,"uuid":"lec0xYiBSmStspGVa6c80Q","version":

{"created":"5060299"},"provided_name":"blog2"}}}}

3.1.4 刪除索引

1)源代碼

@Test

public void deleteIndex(){

// 1 刪除索引

client.admin().indices().prepareDelete("blog2").get();

// 2 關閉連接

client.close();

}

2)查看結果

瀏覽器查看http://hadoop102:9200/blog2

沒有blog2索引了。

{"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such

index","resource.type":"index_or_alias","resource.id":"blog2","index_uuid":"_na_

","index":"blog2"}],"type":"index_not_found_exception","reason":"no such

index","resource.type":"index_or_alias","resource.id":"blog2","index_uuid":"_na_

","index":"blog2"},"status":404}

3.1.5 新建文檔(源數據json串)

當直接在ElasticSearch建立文檔對象時,如果索引不存在的,默認會自動創建,映射采用默認方式。

1)源代碼

@Test

public void createIndexByJson() throws UnknownHostException {

// 1 文檔數據準備

String json = "{" + "\"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();

}

2)結果查看

3.1.6 新建文檔(源數據map方式添加json)

1)源代碼

@Test

public void createIndexByMap() {

// 1 文檔數據準備

Map<String, Object> json = new HashMap<String, Object>();

json.put("id", "2");

json.put("title", "基于Lucene的搜索服務器");

json.put("content", "它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web

接口");

// 2 創建文檔

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();

}

2)結果查看

3.1.7 新建文檔(源數據es構建器添加json)

1)源代碼

@Test

public void createIndex() throws Exception {

// 1 通過es自帶的幫助類,構建json數據

XContentBuilder builder =

XContentFactory.jsonBuilder().startObject().field("id", 3).field("title", "基于

Lucene的搜索服務器").field("content", "它提供了一個分布式多用戶能力的全文搜索引擎,基于

RESTful web接口。")

.endObject();

// 2 創建文檔

IndexResponse indexResponse = client.prepareIndex("blog", "article",

"3").setSource(builder).get();

// 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();

}

2)結果查看

3.1.8 搜索文檔數據(單個索引)

1)源代碼

@Test

public void getData() throws Exception {

// 1 查詢文檔

GetResponse response = client.prepareGet("blog", "article", "1").get();

// 2 打印搜索的結果

System.out.println(response.getSourceAsString());

// 3 關閉連接

client.close();

}

2)結果查看

3.1.9 搜索文檔數據(多個索引)

1)源代碼

@Test

public 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();

}

2)結果查看

{"id":"1","title":"基于Lucene的搜索服務器","content":"它提供了一個分布式多用戶能力的全文

搜索引擎,基于RESTful web接口"}

{"content":"它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web接

口","id":"2","title":"基于Lucene的搜索服務器"}

{"id":3,"titile":"ElasticSearch是一個基于Lucene的搜索服務器","content":"它提供了一個分

布式多用戶能力的全文搜索引擎,基于RESTful web接口。"}

{"content":"它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web接

口","id":"2","title":"基于Lucene的搜索服務器"}

3.1.10 更新文檔數據(update)?

1)源代碼

@Test

public void updateData() throws Throwable {

// 1 創建更新數據的請求對象

UpdateRequest updateRequest = new UpdateRequest();

updateRequest.index("blog");

updateRequest.type("article");

updateRequest.id("3");

updateRequest.doc(XContentFactory.jsonBuilder().startObject()

// 對沒有的字段添加, 對已有的字段替換

.field("title", "基于Lucene的搜索服務器")

.field("content","它提供了一個分布式多用戶能力的全文搜索引擎,基于

RESTful web接口。大數據前景無限")

.field("createDate", "2017-8-22").endObject());

// 2 獲取更新后的值

UpdateResponse indexResponse = client.update(updateRequest).get();

// 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("create:" + indexResponse.getResult());

// 4 關閉連接

client.close();

}

2)結果查看

3.1.11 更新文檔數據(upsert)

設置查詢條件, 查找不到則添加IndexRequest內容,查找到則按照UpdateRequest更新。

@Test

public void testUpsert() throws Exception {

// 設置查詢條件, 查找不到則添加

IndexRequest indexRequest = new IndexRequest("blog", "article", "5")

.source(XContentFactory.jsonBuilder().startObject().field("title", "搜索服務

器").field("content","它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web接口。

Elasticsearch是用Java開發的,并作為Apache許可條款下的開放源碼發布,是當前流行的企業級搜索引

擎。設計用于云計算中,能夠達到實時搜索,穩定,可靠,快速,安裝使用方便。").endObject());

// 設置更新, 查找到更新下面的設置

UpdateRequest upsert = new UpdateRequest("blog", "article", "5")

.doc(XContentFactory.jsonBuilder().startObject().field("user",

"李四").endObject()).upsert(indexRequest);

client.update(upsert).get();

client.close();

}

第一次執行

hadoop102:9200/blog/article/5

3.1.12 刪除文檔數據(prepareDelete)

1)源代碼

@Test

public void deleteData() {

// 1 刪除文檔數據

DeleteResponse indexResponse = client.prepareDelete("blog", "article",

"5").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("found:" + indexResponse.getResult());

// 3 關閉連接

client.close();

}

2)結果查看

3.2 條件查詢QueryBuilder

3.2.1 查詢所有(matchAllQuery)

1)源代碼

@Test

public void matchAllQuery() {

// 1 執行查詢

SearchResponse searchResponse =

client.prepareSearch("blog").setTypes("article")

.setQuery(QueryBuilders.matchAllQuery()).get();

// 2 打印查詢結果

SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對

System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

for (SearchHit hit : hits) {

System.out.println(hit.getSourceAsString());//打印出每條結果

}

// 3 關閉連接

client.close();

}

2)結果查看

3.2.2 對所有字段分詞查詢(queryStringQuery)

1)源代碼

```java

@Test

public void query() {

// 1 條件查詢

SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")

.setQuery(QueryBuilders.queryStringQuery("全文")).get();

// 2 打印查詢結果

SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象

System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

for (SearchHit hit : hits) {

System.out.println(hit.getSourceAsString());//打印出每條結果

}

// 3 關閉連接

client.close();

}

2)結果查看

3.2.3 通配符查詢(wildcardQuery)

* :表示多個字符(0個或多個字符)

?:表示單個字符

1)源代碼

@Test

public 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() + "條");

for (SearchHit hit : hits) {

System.out.println(hit.getSourceAsString());//打印出每條結果

}

// 3 關閉連接

client.close();

}

2)結果查看

3.2.4 詞條查詢(TermQuery)

1)源代碼

@Test

public void termQuery() {

// 1 第一field查詢

SearchResponse searchResponse =

client.prepareSearch("blog").setTypes("article")

.setQuery(QueryBuilders.termQuery("content", "全文")).get();

// 2 打印查詢結果

SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對

System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

for (SearchHit hit : hits) {

System.out.println(hit.getSourceAsString());//打印出每條結果

}

// 3 關閉連接

client.close();

}

2)結果查看

3.2.5 模糊查詢(fuzzy)

@Test

public void fuzzy() {

// 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();

}

3.3 映射相關操作

1)源代碼

@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();

}

2)查看結果

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內容