Elasticsearch6.3.1 JavaAPI

 

依赖

javaAPI官网地址:

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html
<!-- es的客户端-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.3.1</version>
        </dependency>

        <!-- 依赖2.x的log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>

        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

代码:

import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.alibaba.fastjson.JSONObject;

/**
 * ClassName:Crud 简单的增删改查
 * @version
 * @since JDK 1.8
 */
public class Crud {

    public final static String HOST1 = "hdp-1";
    public final static String HOST2 = "hdp-2";
    public final static String HOST3 = "hdp-3";
    // http请求的端口是9200,客户端是9300
    public final static int PORT = 9300;

    private TransportClient client = null;

    /**
     * getConnection:(获取连接).
     *
     * @throws Exception
     */
    @SuppressWarnings({ "resource", "unchecked" })
    @Before
    public void getConnection() throws Exception {
        // 设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "my-es").build();
        // 创建client
        client = new PreBuiltTransportClient(settings)
                .addTransportAddresses(
                        new TransportAddress(InetAddress.getByName(HOST1), PORT),
                        new TransportAddress(InetAddress.getByName(HOST2), PORT),
                        new TransportAddress(InetAddress.getByName(HOST3), PORT)
                );
    }

    /**
     * closeConnection:(关闭连接).
     *
     *
     *
     */
    @After
    public void closeConnection() {
        if (client != null) {
            client.close();
        }
    }

    /**
     * testIndex:(创建索引).
     * @throws IOException
     *
     */
    @Test
    public void testCreateIndex() throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "001");
        jsonObject.put("orderName", "购买元宝");
        jsonObject.put("orderTime", new Date());
        jsonObject.put("price", 1.5);
        jsonObject.put("ip", "192.168.1.111");

        IndexResponse response = client.prepareIndex("rxpay", "order").setSource(jsonObject.toString(), XContentType.JSON).get();
        System.out.println("索引名称:" + response.getIndex());
        System.out.println("类型:" + response.getType());
        System.out.println("文档ID:" + response.getId()); // 第一次使用是1
        System.out.println("当前实例状态:" + response.status());
    }

    /**
     * testQuery:(查询).
     */
    @Test
    public void testQuery() {
        try {
            GetResponse response = client.prepareGet("rxpay", "order", "No5fOW4B4q27MP31ZEzy").execute().actionGet();
            System.out.println(response.getSourceAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * testUpdate:(更新).
     */
    @Test
    public void testUpdate() {
        JSONObject json = new JSONObject();
        json.put("user", "Joe");
        json.put("age", "22");
        json.put("sex", "男");
        json.put("orderTime", "6666666");
        UpdateResponse response = client.prepareUpdate("rxpay", "order", "6W2QKmMBhrIcTC9dgt7A").setDoc(json.toJSONString(), XContentType.JSON).get();
        System.out.println("索引名称:" + response.getIndex());
        System.out.println("类型:" + response.getType());
        System.out.println("文档ID:" + response.getId());
        System.out.println("当前实例状态:" + response.status());
    }

    /**
     * testDelete:(删除).
     */
    @Test
    public void testDelete() {
        DeleteResponse response = client.prepareDelete("rxpay", "order", "6W2QKmMBhrIcTC9dgt7A").get();
        System.out.println("索引名称:" + response.getIndex());
        System.out.println("类型:" + response.getType());
        System.out.println("文档ID:" + response.getId());
        System.out.println("当前实例状态:" + response.status());
    }

判定索引是否存在

//1.设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //2.创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("node1"), 9300));
        //3.获取IndicesAdminClient对象
        IndicesAdminClient indicesAdminClient = client.admin().indices();
        //4.判定索引是否存在
        IndicesExistsResponse response=indicesAdminClient.prepareExists("index1").get();
        System.out.println(response.isExists());

 创建索引

//1.设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //2.创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("node1"), 9300));
        //3.获取IndicesAdminClient对象
        IndicesAdminClient indicesAdminClient = client.admin().indices();
        //4.创建索引
        CreateIndexResponse ciReponse=indicesAdminClient.prepareCreate("index1").get();
        System.out.println(ciReponse.isAcknowledged());

封装工具类


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.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.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ESUtil {
    //集群名,默认值elasticsearch
    private static final String CLUSTER_NAME = "elasticsearch";
    //ES集群中某个节点
    private static final String HOSTNAME = "node1";
    //连接端口号
    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;
    }
}

测试程序


import cn.hadron.es.*;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
public class ESUtilDemo {
    public static void main(String[] args) {
        //1.判定索引是否存在
        boolean flag=ESUtil.isExists("index1");
        System.out.println("isExists:"+flag);
        //2.创建索引
        flag=ESUtil.createIndex("index1", 3, 0);
        System.out.println("createIndex:"+flag);
        //3.设置Mapping
        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("index1", "blog", builder.string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

批量操作、查询

@Test
    public void testMultiGet() {
        MultiGetRequestBuilder multiGetRequestBuilder = client.prepareMultiGet();
        MultiGetRequestBuilder person = multiGetRequestBuilder.add("my-index", "persion", "1", "2", "3");

        MultiGetResponse multiGetItemResponses = person.get();

        Iterator<MultiGetItemResponse> iterator = multiGetItemResponses.iterator();
        while(iterator.hasNext()) {
            MultiGetItemResponse next = iterator.next();
            GetResponse response = next.getResponse();
            System.out.println(response.getSourceAsString());
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值