ElasticSearch JAVA transportClient

创建maven工程

pom.xml 中加入 Elasticsearch 的依赖:

    	<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>7.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.2.0</version>
        </dependency>
    	<dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>

TransportClient

TransportClient API在elasticSearch8中将会被移除,后将使用 HighLevelClient API进行连接。

连接集群

package elasticSearch.transportClient;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

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

/**
 * @author 
 * @description TransportClient 在elasticSearch8中将会被移除
 * @date 2019/7/31
 */
public class ESClientTest {
    public static Client client;

    /**
     * init ES client
     * @return
     */
    public static Client initEsClient() throws UnknownHostException {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
        Settings esSettings = Settings.builder().put("cluster.name", "unisinsight").build();//设置ES实例的名称
        client = new PreBuiltTransportClient(esSettings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("master01"),9300))
                .addTransportAddress(new TransportAddress(InetAddress.getByName("slave01"),9300));
        return client;
    }

    /**
     * Close ES client
     */
    public static void closeEsClient() {
        client.close();
    }
}

index API

package elasticSearch.transportClient;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;

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

/**
 * @author [tu.tengfei]
 * @description 
 * @date 2019/8/1
 */
public class IndexAPI {
    private static Client client;

    static {
        try {
            client = ESClientTest.initEsClient();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        bulkAPI(client);
        ESClientTest.closeEsClient();
    }

    /**
     * 添加数据
     *
     * @throws IOException
     */
    public static void IndexAPI(Client client) throws IOException {
        XContentBuilder field = jsonBuilder()
                .startObject()
                .field("behavior_en", "walking")
                .field("behavior_ch", "走路")
                .field("score", 0)
                .endObject();
        IndexResponse behavior = client.prepareIndex("behavior", "_doc", "1").setSource(field).get();
        System.out.println(behavior);
    }

    public static void getIndex(Client client) {
        GetResponse documentFields = client.prepareGet("behavior", "_doc", "1").get();
        System.out.println(documentFields);
    }

    public static void deleteIndex(Client client) {
        DeleteResponse deleteResponse = client.prepareDelete("behavior", "_doc", "1").get();
        System.out.println(deleteResponse);
    }

    /**
     * bulkAPI 批量操作,index不存在时会自动创建
     *
     * @param client
     * @throws IOException
     */
    public static void bulkAPI(Client client) throws IOException {
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        bulkRequestBuilder.add(client.prepareIndex("twitter", "_doc", "1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                        .endObject()
                )
        );

        bulkRequestBuilder.add(client.prepareIndex("twitter", "_doc", "2")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                        .endObject()
                )
        );


        BulkResponse bulkItemResponses = bulkRequestBuilder.get();
        if (bulkItemResponses.hasFailures()) {
            System.out.println("插入失败!" + bulkItemResponses.buildFailureMessage());
        }
    }
}

search API

package elasticSearch.transportClient;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;

import java.io.IOException;
import java.net.UnknownHostException;

/**
 * @author [tu.tengfei]
 * @description
 * @date 2019/8/1
 */
public class SearchAPI {
    private static Client client;

    static {
        try {
            client = ESClientTest.initEsClient();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        searchQuery(client);
        ESClientTest.closeEsClient();
    }

    public static void searchQuery(Client client) {
        SearchResponse searchResponse = client.prepareSearch("twitter")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.matchQuery("message", "Elasticsearch"))
//                .setPostFilter(QueryBuilders.rangeQuery("age").from(11).to(21))
                .setFrom(0)
                .setSize(60)
                .setExplain(true)
                .get();
        System.out.println(searchResponse);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值