ES6.6.2 使用小结 - ES工具类使用

本文提供了一个封装好的Elasticsearch工具类,包含基本的ES操作方法,如创建索引、设置mapping等,并通过示例展示了如何使用这些方法进行索引创建及文档的增删改查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.以下是封装了ES常用的基本方法,可以用来做一些简单的测试。

  如:获取ES的TransportClient/IndicesAdminClient、判定索引是否存在、创建索引、设置mapping、删除索引、插入文档。

package com.bas.util;

import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

/**
 * ES工具类
 */
public class ESUtil {
    //集群名,默认值elasticsearch
    private static final String CLUSTER_NAME = "TestCluster";
    //ES集群中某个节点
    private static final String HOSTNAME = "localhost";
    //连接端口号
    private static final int TCP_PORT = 9300;
    //构建Settings对象
    private static Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME).build();
    //TransportClient对象,用于连接ES集群
    private static volatile TransportClient client;

    /**
     * 同步synchronized(*.class)代码块的作用和synchronized static方法作用一样,
     * 对当前对应的*.class进行持锁,static方法和.class一样都是锁的该类本身,同一个监听器
     *
     * @return
     * @throws UnknownHostException
     */
    public static TransportClient getClient() {
        if (client == null) {
            synchronized (TransportClient.class) {
                try {
                    client = new PreBuiltTransportClient(settings)
                            .addTransportAddress(new TransportAddress(InetAddress.getByName(HOSTNAME), TCP_PORT));
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        return client;
    }

    /**
     * 获取索引管理的IndicesAdminClient
     */
    public static IndicesAdminClient getAdminClient() {
        return getClient().admin().indices();
    }

    /**
     * 判定索引是否存在
     *
     * @param indexName
     * @return
     */
    public static boolean isExists(String indexName) {
        IndicesExistsResponse response = getAdminClient().prepareExists(indexName).get();
        return response.isExists() ? true : false;
    }

    /**
     * 创建索引
     *
     * @param indexName
     * @return
     */
    public static boolean createIndex(String indexName) {
        CreateIndexResponse createIndexResponse = getAdminClient()
                .prepareCreate(indexName.toLowerCase())
                .get();
        return createIndexResponse.isAcknowledged() ? true : false;
    }

    /**
     * 创建索引
     *
     * @param indexName 索引名
     * @param shards    分片数
     * @param replicas  副本数
     * @return
     */
    public static boolean createIndex(String indexName, int shards, int replicas) {
        Settings settings = Settings.builder()
                .put("index.number_of_shards", shards)
                .put("index.number_of_replicas", replicas)
                .build();
        CreateIndexResponse createIndexResponse = getAdminClient()
                .prepareCreate(indexName.toLowerCase())
                .setSettings(settings)
                .execute().actionGet();
        return createIndexResponse.isAcknowledged() ? true : false;
    }

    /**
     * 为索引indexName设置mapping
     *
     * @param indexName
     * @param typeName
     * @param mapping
     */
    public static void setMapping(String indexName, String typeName, String mapping) {
        getAdminClient().preparePutMapping(indexName)
                .setType(typeName)
                .setSource(mapping, XContentType.JSON)
                .get();
    }

    /**
     * 删除索引
     *
     * @param indexName
     * @return
     */
    public static boolean deleteIndex(String indexName) {
        DeleteIndexResponse deleteResponse = getAdminClient()
                .prepareDelete(indexName.toLowerCase())
                .execute()
                .actionGet();
        return deleteResponse.isAcknowledged() ? true : false;
    }

    /**
     * 插入文档
     *
     * @param indexName 索引名
     * @param type      类型
     * @param doc       XContentBuilder
     */
    public static void insertDocument(String indexName, String type, XContentBuilder doc) {
        IndexResponse response = getClient().prepareIndex(indexName, type)
                .setSource(doc)
                .get();
        System.out.println(response.status());
    }

    /**
     * 插入文档
     *
     * @param indexName 索引名
     * @param type      类型
     * @param json      Json格式串
     */
    public static void insertDocument(String indexName, String type, String json) {
        IndexResponse response = getClient().prepareIndex(indexName, type)
                .setSource(json, XContentType.JSON)
                .get();
        System.out.println(response.status());
    }

    /**
     * 查询文档
     *
     * @param indexName 索引名
     * @param type      类型
     * @param id        文档id
     * @return
     */
    public static String selectDocument(String indexName, String type, String id) {
        GetResponse response = getClient().prepareGet(indexName, type, id).get();
        System.out.println(response.isExists());
        System.out.println(response.getIndex());
        System.out.println(response.getType());
        System.out.println(response.getId());
        System.out.println(response.getVersion());
        return response.getSourceAsString();
    }

    /**
     * 删除文档
     *
     * @param indexName 索引名
     * @param type      类型
     * @param id        文档id
     */
    public static void deleteDocument(String indexName, String type, String id) {
        DeleteResponse response = getClient().prepareDelete(indexName, type, id).get();
        //删除成功返回OK,否则返回NOT_FOUND
        System.out.println(response.status());
        //返回被删除文档的类型
        System.out.println(response.getType());
        //返回被删除文档的ID
        System.out.println(response.getId());
        //返回被删除文档的版本信息
        System.out.println(response.getVersion());
    }

    /**
     * 修改文档
     *
     * @param indexName 索引名
     * @param type      类型
     * @param id        文档id
     * @param doc       Json
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void updateDocument(String indexName, String type, String id, XContentBuilder doc) throws ExecutionException, InterruptedException {
        UpdateRequest request = new UpdateRequest();
        request.index(indexName).type(type).id(id).doc(doc);
        UpdateResponse response = getClient().update(request).get();
        //更新成功返回OK,否则返回NOT_FOUND
        System.out.println(response.status());
        //返回被更新文档的类型
        System.out.println(response.getType());
        //返回被更新文档的ID
        System.out.println(response.getId());
        //返回被更新文档的版本信息
        System.out.println(response.getVersion());
    }

    /**
     * 更新数据,存在文档则使用updateDoc,不存在则使用insertDoc
     *
     * @param indexName 索引名
     * @param type      类型
     * @param id        文档id
     * @param insertDoc 新文档
     * @param updateDoc 更新文档
     */
    public static void upsertDocument(String indexName, String type, String id, XContentBuilder insertDoc, XContentBuilder updateDoc) throws ExecutionException, InterruptedException {
        IndexRequest indexRequest = new IndexRequest(indexName, type, id)
                .source(insertDoc);
        UpdateRequest updateRequest = new UpdateRequest(indexName, type, id)
                .doc(updateDoc).upsert(indexRequest);
        UpdateResponse response = getClient().update(updateRequest).get();
        //upsert操作成功返回OK,否则返回NOT_FOUND
        System.out.println(response.status());
        //返回被操作文档的类型
        System.out.println(response.getType());
        //返回被操作文档的ID
        System.out.println(response.getId());
        //返回被操作文档的版本信息
        System.out.println(response.getVersion());
    }

}

2.结合ESUtil.java ,来做一些测试。首先是创建type为"blog"的Mapping,运行CreateDemo.test():

package com.bas.demo;

import com.bas.util.ESUtil;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.jupiter.api.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class CreateDemo {

    /**
     * 创建Index
     * @param args
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws UnknownHostException {
        //1.设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "TestCluster").build();
        //2.创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
        //3.获取IndicesAdminClient对象
        IndicesAdminClient indicesAdminClient = client.admin().indices();
        //4.创建索引
        CreateIndexResponse ciReponse=indicesAdminClient.prepareCreate("app_account").get();
        System.out.println(ciReponse.isAcknowledged());
    }

    /**
     * 创建Mapping
     */
    @Test
    public void test(){
        try {
            XContentBuilder builder = jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("id")
                    .field("type", "long")
                    .endObject()
                    .startObject("title")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .field("search_analyzer", "ik_max_word")
                    .field("boost", 2)
                    .endObject()
                    .startObject("content")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .field("search_analyzer", "ik_max_word")
                    .endObject()
                    .startObject("postdate")
                    .field("type", "date")
                    .field("format", "yyyy-MM-dd HH:mm:ss")
                    .endObject()
                    .startObject("url")
                    .field("type", "keyword")
                    .endObject()
                    .endObject()
                    .endObject();
            System.out.println(builder.string());
            ESUtil.setMapping("app_account", "blog", builder.string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

、3.接下来,以两种方式插入文档到blog:

package com.bas.demo;

import com.bas.util.ESUtil;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class InsertDemo {
    public static void main(String[] args) throws IOException {
        // 方式一
        String json = "{" +
                "\"id\":\"1\"," +
                "\"title\":\"Java連接ES\"," +
                "\"content\":\"abcdefg。\"," +
                "\"postdate\":\"2019-03-24 14:38:00\"," +
                "\"url\":\"bas.com\"" +
                "}";
        System.out.println(json);

        ESUtil.insertDocument("app_account", "blog", json);

        // 方式二
        XContentBuilder doc = jsonBuilder()
                .startObject()
                .field("id","2")
                .field("title","Java插入数据到ES")
                .field("content","abcedfasdasd")
                .field("postdate","2019-03-24 14:38:00")
                .field("url","bas.com")
                .endObject();
        ESUtil.insertDocument("app_account", "blog", doc);

    }
}

结果如图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值