1. 程式人生 > 實用技巧 >elasticsearch的java api

elasticsearch的java api

一、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>A02elasticsearch</artifactId>
    <version>1.0
-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch --> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.4
.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>7.4
.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-to-slf4j --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-to-slf4j</artifactId> <version>2.13.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.30</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.9</source> <target>1.9</target> </configuration> </plugin> </plugins> </build> </project>

二、bean

package com.wuxi.bean;

import lombok.Data;

@Data
public class Article {
    private Long id;
    private String title;
    private String content;
}

三、測試

package com.wuxi.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuxi.bean.Article;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
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.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MyElasticSearchTest {
    /**
     * 建立索引庫
     *
     * @throws Exception
     */
    @Test
    public void createIndex() throws Exception {
        //1、建立一個Settings物件,相當於是一個配置資訊。主要配置叢集名稱。
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //2、建立一個客戶端client物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //3、使用client物件建立一個索引庫
        Map<String, Object> settingsMap = new HashMap<>();
        Map<String, Object> indexMap = new HashMap<>();
        indexMap.put("number_of_shards", "5");
        indexMap.put("number_of_replicas", "1");
        settingsMap.put("index", indexMap);
        client.admin().indices().prepareCreate("index_hello").setSettings(settingsMap)
                //執行操作
                .get();
        //4、關閉client物件
        client.close();
    }

    /**
     * 新增mapping對映
     *
     * @throws Exception
     */
    @Test
    public void setMappings() throws Exception {
        //建立一個Settings物件
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //建立一個TransportClient物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //建立一個Mappings資訊
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("properties")
                .startObject("id")
                .field("type", "long")
                .field("store", true)
                .endObject()
                .startObject("title")
                .field("type", "text")
                .field("store", true)
                .field("analyzer", "ik_smart")
                .endObject()
                .startObject("content")
                .field("type", "text")
                .field("store", true)
                .field("analyzer", "ik_smart")
                .endObject()
                .endObject()
                .endObject();
        //使用client把mapping資訊設定到索引庫中
        client.admin().indices()
                .preparePutMapping("index_hello")
                .setType("_doc")
                .setSource(builder)
                .get();
        //關閉client物件
        client.close();
    }

    /**
     * 新增文件
     *
     * @throws Exception
     */
    @Test
    public void testAddDocument() throws Exception {
        //建立一個Settings物件
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //建立一個TransportClient物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //建立一個文件物件
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", 1l)
                .field("title", "這是文件的標題")
                .field("content", "這是文件的內容,是一段中文")
                .endObject();
        //把文件物件新增到索引庫
        client.prepareIndex()
                .setIndex("index_hello")
                .setType("_doc")
                .setId("1")
                .setSource(builder)
                .get();
        //關閉
        client.close();
    }

    /**
     * json方式新增文件
     *
     * @throws Exception
     */
    @Test
    public void testAddDocument2() throws Exception {
        //建立一個Settings物件
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //建立一個TransportClient物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //建立生成json字串
        Article article = new Article();
        article.setId(2l);
        article.setTitle("使用json方式新增文件");
        article.setContent("就統籌推進常態化疫情防控和經濟社會發展工作、謀劃“十四五”時期經濟社會發展進行調研。");
        String jsonDocument = new ObjectMapper().writeValueAsString(article);
        //使用client物件把文件寫入索引庫
        client.prepareIndex("index_hello", "_doc", "2")
                .setSource(jsonDocument, XContentType.JSON)
                .get();
        //關閉
        client.close();
    }

    /**
     * 根據id查詢文件
     *
     * @throws Exception
     */
    @Test
    public void testSearchById() throws Exception {
        //建立一個Settings物件
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //建立一個TransportClient物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //建立一個查詢物件
        QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1", "2");
        //執行查詢
        SearchResponse searchResponse = client.prepareSearch("index_hello")
                .setTypes("_doc")
                .setQuery(queryBuilder)
                .get();
        //取查詢結果
        SearchHits searchHits = searchResponse.getHits();
        //取查詢結果的總記錄數
        System.out.println("查詢結果總記錄數:" + searchHits.getTotalHits());
        //查詢結果列表
        Iterator<SearchHit> iterator = searchHits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next();
            //列印文件物件,以json格式輸出
            System.out.println(searchHit.getSourceAsString());
            //取文件的屬性
            System.out.println("--------文件的屬性");
            Map<String, Object> document = searchHit.getSourceAsMap();
            System.out.println(document.get("id"));
            System.out.println(document.get("title"));
            System.out.println(document.get("content"));
        }
        //關閉
        client.close();
    }

    /**
     * 根據關鍵詞查詢文件
     *
     * @throws Exception
     */
    @Test
    public void testSearchByTerm() throws Exception {
        //建立一個Settings物件
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //建立一個TransportClient物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //建立一個查詢物件
        QueryBuilder queryBuilder = QueryBuilders.termQuery("title", "文件");
        //執行查詢
        SearchResponse searchResponse = client.prepareSearch("index_hello")
                .setTypes("_doc")
                .setQuery(queryBuilder)
                .get();
        //取查詢結果
        SearchHits searchHits = searchResponse.getHits();
        //取查詢結果的總記錄數
        System.out.println("查詢結果總記錄數:" + searchHits.getTotalHits());
        //查詢結果列表
        Iterator<SearchHit> iterator = searchHits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next();
            //列印文件物件,以json格式輸出
            System.out.println(searchHit.getSourceAsString());
            //取文件的屬性
            System.out.println("--------文件的屬性");
            Map<String, Object> document = searchHit.getSourceAsMap();
            System.out.println(document.get("id"));
            System.out.println(document.get("title"));
            System.out.println(document.get("content"));
        }
        //關閉
        client.close();
    }

    /**
     * 根據分詞查詢,分頁查詢,高亮顯示
     *
     * @throws Exception
     */
    @Test
    public void testQueryStringQuery() throws Exception {
        //建立一個Settings物件
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //建立一個TransportClient物件
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //建立一個查詢物件
        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("這是一個文件")
                .defaultField("title");
        //高亮顯示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        //執行分頁查詢
        SearchResponse searchResponse = client.prepareSearch("index_hello")
                .setTypes("_doc")
                .setQuery(queryBuilder)
                //頁數
                .setFrom(0)
                //每頁條數
                .setSize(5)
                //設定高亮
                .highlighter(highlightBuilder)
                .get();
        //取查詢結果
        SearchHits searchHits = searchResponse.getHits();
        //取查詢結果的總記錄數
        System.out.println("查詢結果總記錄數:" + searchHits.getTotalHits());
        //查詢結果列表
        Iterator<SearchHit> iterator = searchHits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next();
            //列印文件物件,以json格式輸出
            System.out.println(searchHit.getSourceAsString());
            //取文件的屬性
            System.out.println("--------文件的屬性");
            Map<String, Object> document = searchHit.getSourceAsMap();
            System.out.println(document.get("id"));
            System.out.println(document.get("title"));
            System.out.println(document.get("content"));
            System.out.println("********高亮顯示");
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            System.out.println(highlightFields);
            //取title高亮顯示的結果
            HighlightField field = highlightFields.get("title");
            Text[] fragments = field.getFragments();
            if (fragments != null) {
                String title = fragments[0].toString();
                System.out.println(title);
            }
        }
        //關閉
        client.close();
    }
}