Elasticsearch JestClient 使用

祖奇
2023-12-01

一、索引操作

//创建索引
     public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 创建索引
        CreateIndex createIndex = new CreateIndex.Builder("my_index").build();
        JestResult result = jestClient.execute(createIndex);

        // 5. 输出创建结果
        System.out.println(result.getJsonString());

    }
//删除索引
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 删除索引
        DeleteIndex deleteIndex = new DeleteIndex.Builder("my_index").build();
        JestResult result = jestClient.execute(deleteIndex);

        // 5. 输出创建结果
        System.out.println(result.getJsonString());

    }
//设置Mapping
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 创建 json 格式的 mapping
        /**
         * {
         *     "mappings":{
         *         "properties":{
         *             "field1":{
         *                 "type":"keyword"
         *             },
         *             "field2":{
         *                 "type":"byte"
         *             }
         *         }
         *     }
         * }
         */
        Map<String, Object> map = new HashMap<String, Object>() {{
            this.put("mappings", new HashMap<String, Object>() {{
                this.put("properties", new HashMap<String, Object>() {{
                    this.put("name", new HashMap<String, String>() {{
                        //this.put("type", "keyword");
                    }});
                    this.put("age", new HashMap<String, String>() {{
                        //this.put("type", "integer");
                    }});
                }});
            }});
        }};
        String mapping = JSONObject.toJSONString(map);

        // 5. 创建索引
        // PutMapping putMapping = new PutMapping.Builder(indexName, indexType, indexMapping).build();
        CreateIndex createIndex = new CreateIndex.Builder("my_index").settings(mapping).build();
        JestResult result = jestClient.execute(createIndex);

        // 6. 输出创建结果
        System.out.println(result.getJsonString());

    }
//获取Mapping
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 获取 mapping
        GetMapping getMapping = new GetMapping.Builder().addIndex("my_index").build();
        JestResult result = jestClient.execute(getMapping);

        // 6. 输出获取结果
        System.out.println(result.getJsonString());

    }

二、文档操作

public class Book {

    @JestId // 自动生成 id,
    private String id;
    private String name;
    private String author;
    private String desc;

    public Book(String id, String name, String author, String desc) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.desc = desc;
    }
}
//新增/修改文档
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 准备数据
        Book book = new Book("001", "斗破苍穹", "天蚕土豆", "这是斗气的世界");

        // 4. 首先会判断索引是否存在,不存在则根据文档创建索引,然后判断 id 是否存在,存在就是更新文档
        Index index = new Index.Builder(book).index("my_index").type("_doc").build();
        JestResult result = jestClient.execute(index);

        // 5. 输出创建结果
        System.out.println(result.getJsonString());

    }
//批量新增
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 批量创建文档
        Bulk.Builder bulk = new Bulk.Builder().defaultIndex("my_index").defaultType("_doc");
        List<Book> list = new ArrayList<Book>() {{
            this.add(new Book("001", "斗破苍穹", "天蚕土豆", "这是斗气的世界"));
            this.add(new Book("002", "完美世界", "辰东", "遮天前传"));
            this.add(new Book("003", "盘龙", "我吃西红柿", "神奇的戒指"));
            this.add(new Book("004", "诛仙", "萧鼎", "天地不仁,以万物为刍狗"));
            this.add(new Book("005", "大主宰", "天蚕土豆", "大千世界,位面交汇"));
        }};
        for (Book book : list) {
            // 如未设置唯一 id 值,则唯一 id 会默认生成,索引操作为添加操作
            Index index = new Index.Builder(book).build();
            bulk.addAction(index);
        }
        BulkResult result = jestClient.execute(bulk.build());

        System.out.println(result.getJsonString());
    }
//根据id查询文档
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 查询文档
        Get get = new Get.Builder("my_index", "001").type("_doc").build();
        JestResult result = jestClient.execute(get);

        // 5. 输出查询结果
        System.out.println(result.getJsonString());
    }
//根据条件查询文档
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 查询文档
        // 4.1 构造查询条件
        // 4.1.1 单 field 不分词查询
        // TermQueryBuilder termQueryBuilder = new TermQueryBuilder(fieldName, value);
        // 4.1.2 单 field 多词不分词查询
        // TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder("", "value1", "value2");
        // 4.1.3 单 field 分词查询
        // MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder(fieldName, value);
        // 4.1.4 多 field 分词查询
        MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder("斗气", "desc");
        // 转化为 ES 查询,默认分词后 and 连接,可使用 defaultOperator(Operator.AND) 修改
        SearchSourceBuilder query = new SearchSourceBuilder().query(multiMatchQueryBuilder);
        // 4.2 构造查询
        Search search = new Search.Builder(query.toString()).build();
        // 4.3 执行查询
        JestResult result = jestClient.execute(search);

        // 5. 输出查询结果
        System.out.println(result.getJsonString());
    }
//区间搜索
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4.1 构建区间搜索条件
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("id").gt("002").lte("003");
        // 4.2 解析为 ES 查询
        SearchSourceBuilder query = new SearchSourceBuilder().query(rangeQueryBuilder);
        // 4.3 构建查询
        Search search = new Search.Builder(query.toString()).build();
        // 4.4 执行查询
        JestResult result = jestClient.execute(search);

        // 5. 输出查询结果
        System.out.println(result.getJsonString());
    }
//删除文档
     public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4. 删除文档
        Delete delete = new Delete.Builder("001").index("my_index").type("_doc").build();
        JestResult result = jestClient.execute(delete);

        // 5. 输出删除结果
        System.out.println(result.getJsonString());
    }
//分页
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4.1 构建区间搜索条件
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("id").gt("002").lte("003");
        // 4.2 解析为 ES 查询并添加分页
        SearchSourceBuilder query = new SearchSourceBuilder().query(rangeQueryBuilder).from(0).size(1);
        // 4.3 构建查询
        Search search = new Search.Builder(query.toString()).build();
        // 4.4 执行查询
        JestResult result = jestClient.execute(search);

        // 5. 输出查询结果
        System.out.println(result.getJsonString());
    }
//高亮
    public static void main(String[] args) throws IOException {
        // 1. 创建 ES 连接池
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 2. 配置 ES 信息
        HttpClientConfig config = new HttpClientConfig.Builder("http://127.0.0.1:9200").build();
        jestClientFactory.setHttpClientConfig(config);

        // 3. 获取 ES 连接
        JestClient jestClient = jestClientFactory.getObject();

        // 4.1 构建搜索条件
        MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder("天世界", "author", "desc");
        // 4.2 转化为 ES 搜索
        SearchSourceBuilder query = new SearchSourceBuilder().query(multiMatchQueryBuilder);
        // 4.3 配置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("author");
        highlightBuilder.field("desc");
        highlightBuilder.preTags("<em>").postTags("</em>");
        highlightBuilder.fragmentSize(500);
        query.highlighter(highlightBuilder);
        // 4.4 构建查询
        Search search = new Search.Builder(query.toString()).build();
        // 4.5 执行查询, 使用 SearchResult 接收
        SearchResult result = jestClient.execute(search);

        // 5.1 遍历查询结果
        List<SearchResult.Hit<Book, Void>> hits = result.getHits(Book.class);
        for (SearchResult.Hit<Book, Void> hit : hits) {
            // 5.2 获取高亮集合
            Map<String, List<String>> highlight = hit.highlight;
            for (String s : highlight.keySet()) {
                // 5.3 输出高亮结果
                System.out.println("高亮显示:" + highlight.get(s).get(0));
            }
        }
    }

.三、导入包及pom文件引包

import com.alibaba.fastjson.JSONObject;
import com.sdcqjy.cloud.common.util.JsonUtils;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Delete;
import io.searchbox.core.Get;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.mapping.GetMapping;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


        <dependency>																																																
            <groupId>io.searchbox</groupId>																																																
            <artifactId>jest</artifactId>
            <version>6.3.1</version>																																																
        </dependency>	
 类似资料: