ElasticSearch實戰:使用java連接elasticsearch集羣,並進行相關操作

1.需求:

使用java連接elasticsearch集羣,並進行相關操作

2.代碼:

(1)pom.xml
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</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>
(2)ES_test.java
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
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.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;

public class ES_test {

    private TransportClient client;

    @SuppressWarnings("unchecked")
    @Before
    public void getClient() throws UnknownHostException {

        // 1 設置連接的集羣名稱
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        // 2 連接集羣
        client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.121"), 9300));

        // 3 打印集羣名稱
         //System.out.println(client.toString());
    }

    @Test
    public void createIndex_blog() {
        // 創建索引

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

        client.close();
    }

    @Test
    public void deleteIndex() {
        // 刪除索引
        client.admin().indices().prepareDelete("blog").get();

        client.close();
    }

    @Test
    public void insertByJson() {
        // 使用json常見document

        // 1、文檔數據準備
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基於Lucene的搜索服務器\","
                + "\"content\":\"它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口\"" + "}";

        // 2 在es中創建文檔
        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("result: " + indexResponse.getResult());

        client.close();
    }

    @Test
    public void insertByMap() {
        // 使用Map創建document
        // 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("result: " + indexResponse.getResult());

        client.close();
    }

    @Test
    public void insertByXContent() throws Throwable {
        // 使用XContentBuilder創建document

        // 1 通過es自帶的幫助類,構建json數據
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 5)
                .field("title", "基於Lucene的搜索服務器").field("content", "sdfs它sdfsdfsdf提供了一個分佈式多用戶能力的全文搜索引擎,基於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("result: " + indexResponse.getResult());

        client.close();

    }

    @Test
    public void getData() {
        // 查詢文檔
        GetResponse response = client.prepareGet("blog", "article", "1").get();

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

        client.close();

    }

    @Test
    public void getMultiData() {
        // 查詢多個文檔

        MultiGetResponse response = client.prepareMultiGet()
                .add("blog", "article", "1")
                .add("blog", "article", "2", "3")
                .add("blog", "article", "2").get();

        //遍歷返回結果
        for (MultiGetItemResponse multiGetItemResponse : response) {
            GetResponse getResponse = multiGetItemResponse.getResponse();

            //獲取查詢結果
            if (getResponse.isExists()) {
                String sourceAsString = getResponse.getSourceAsString();
                System.out.println(sourceAsString);

            }
        }

        client.close();
    }
    @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());// NOOP = NO
																	// OPeration
																	// ;
																	// result=updated
																	// 表示更新成功

		// 4 關閉連接
		client.close();
	}

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

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

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

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

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

	@Test
	public void termQuery() {

		// 類似於 mysql 中 = 

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

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

	@Test
	public void createMapping() throws Exception {

		// 1設置mapping
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("article")
				.startObject("properties")
				.startObject("id1")
				.field("type", "text")
				.field("store", "true").endObject()
				.startObject("title2")
				.field("type", "text").field("store", "false").endObject()
				.startObject("content")
				.field("type", "text").field("store", "true").endObject()
				.endObject().endObject().endObject();

		// 2 添加mapping
		PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);

		client.admin().indices().putMapping(mapping).get();

		// 3 關閉資源
		client.close();
	}

	// 創建使用ik分詞器的mapping
	@Test
	public void createMapping_ik() throws Exception {

		// 1設置mapping
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("article")
				.startObject("properties")
				.startObject("id1")
				.field("type", "text").field("store", "true")
				.field("analyzer", "ik_smart")
				.endObject()
				.startObject("title2").field("type", "text")
				.field("store", "false").field("analyzer", "ik_smart").
				endObject().startObject("content")
				.field("type", "text").field("store", "true")
				.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();
	}

	// 創建文檔,以map形式
	@Test
	public void createDocumentByMap_forik() {

		HashMap<String, String> map = new HashMap<String, String>();
		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();
	}

	// 詞條查詢
	@Test
	public void queryTerm_forik() {

		// 分析結果:因爲是默認被standard analyzer分詞器分詞,大寫字母全部轉爲了小寫字母,並存入了倒排索引以供搜索。term是確切查詢, 必須要匹配到大寫的Name。
		SearchResponse response = client.prepareSearch("blog4")
				.setTypes("article")
				.setQuery(QueryBuilders.termQuery("content", "web"))
				.get();

		// 獲取查詢命中結果
		SearchHits hits = response.getHits();

		System.out.println("結果條數:" + hits.getTotalHits());

		for (SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}

}


3.結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章