ElasticSearch入门教程【五】- TransportClient客户端

教程列表

ElasticSearch入门教程【一】- 简介
ElasticSearch入门教程【二】- 安装
ElasticSearch入门教程【三】- Head插件
ElasticSearch入门教程【四】- 基本用法
ElasticSearch入门教程【五】- TransportClient客户端
ElasticSearch入门教程【六】- spring-boot-starter-data-elasticsearch

文章目录

        • 一、版本信息
        • 二、Maven依赖
        • 三、代码实现
          • 1. 配置类
          • 2. 增删改查等操作
        • 四、工程目录结构
        • 五、参考文档

TransportClient是Elasticsearch的一个客户端,可以创建客户端连接对Elasticsearch进行操作,客户端最好和Elasticsearch版本相同。

一、版本信息

Springboot 2.0.9.RELEASE

transport 5.6.16

Elasticsearch 5.6.16

二、Maven依赖


<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.0.9.RELEASEversion> 
		<relativePath/> 
	parent>
	<groupId>com.rkyaogroupId>
	<artifactId>spring-boot-elasticsearch-transportartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>spring-boot-elasticsearch-transportname>
	<description>Demo project for Spring Bootdescription>

	<properties>
		<java.version>1.8java.version>
	properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintagegroupId>
					<artifactId>junit-vintage-engineartifactId>
				exclusion>
			exclusions>
		dependency>

		
		<dependency>
			<groupId>org.elasticsearch.clientgroupId>
			<artifactId>transportartifactId>
			<version>5.6.16version>
		dependency>
		<dependency>
			<groupId>org.apache.logging.log4jgroupId>
			<artifactId>log4j-coreartifactId>
			<version>2.7version>
		dependency>

		
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<version>1.18.12version>
			<scope>providedscope>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

project>

三、代码实现

1. 配置类
package com.rkyao.spring.boot.elasticsearch.transport.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
public class ElasticsearchConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {
        // 设置elasticsearch集群地址 ip和端口
        InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName("192.168.255.150"), 9300);

        // 设置elasticsearch集群名称
        Settings settings = Settings.builder()
                .put("cluster.name", "rkyao-es-cluster")
                .build();

        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(address);
        return client;
    }

}
2. 增删改查等操作
package com.rkyao.spring.boot.elasticsearch.transport;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TransportClientTest {

    @Autowired
    private TransportClient transportClient;

    /**
     * 新增数据
     * 
     * @throws Exception
     */
    @Test
    public void testAdd() throws Exception {
        String index = "people";
        String type = "student";

        // 要新增的文档参数
        String name = "rkyao";
        String address = "SD";
        int age = 25;
        Date birthday = new Date();
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name", name)
                .field("address", address)
                .field("age", age)
                .field("birthday", birthday.getTime())
                .endObject();

        // 发送新增请求
        IndexResponse response = transportClient.prepareIndex(index, type)
                .setSource(builder)
                .get();
        // 新增文档的id
        String id = response.getId();
        System.out.println(id);
    }

    /**
     * 根据id查询
     *
     * @throws Exception
     */
    @Test
    public void testGet() throws Exception {
        String index = "people";
        String type = "student";

        String id = "AXNn8Ab1Gys1ttDyexel";
        // 发送查询请求
        GetResponse response = transportClient.prepareGet(index, type, id).get();
        if (!response.isExists()) {
            System.out.println("Not found.");
            return;
        }
        // 查询结果
        Map<String, Object> resultMap = response.getSource();
        System.out.println(resultMap);
    }

    /**
     * 复合查询
     *
     * @throws Exception
     */
    @Test
    public void testQuery() throws Exception {
        String index = "people";
        String type = "student";

        String address = "SD";

        // 根据年龄范围查询 [20, 25]
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").from(20).to(25);

        // 根据地址查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("address", address))
                .filter(rangeQueryBuilder);

        SearchRequestBuilder builder = transportClient.prepareSearch(index)
                .setTypes(type)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQueryBuilder)
                .setFrom(0)
                .setSize(10); // 查询10条数据
        // 发送查询请求
        SearchResponse response = builder.get();

        // 查询结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            resultList.add(hit.getSource());
        }

        System.out.println(resultList);
    }

    /**
     * 根据id删除数据
     *
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception {
        String index = "people";
        String type = "student";

        String id = "AXNn8Ab1Gys1ttDyexel";

        // 发送删除请求
        DeleteResponse response = transportClient.prepareDelete(index, type, id).get();
        System.out.println(response.getResult().toString());
    }

    /**
     * 更新数据
     *
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        String index = "people";
        String type = "student";

        // 要修改的文档参数
        String id = "AXNn8Ab1Gys1ttDyexel";
        String address = "SD";
        int age = 23;

        XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
                .field("address", address)
                .field("age", age)
                .endObject();

        UpdateRequest request = new UpdateRequest(index, type, id);
        request.doc(builder);

        UpdateResponse response = transportClient.update(request).get();
        System.out.println(response.getResult().toString());
    }

}

四、工程目录结构

ElasticSearch入门教程【五】- TransportClient客户端_第1张图片

五、参考文档

https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.6/transport-client.html

你可能感兴趣的:(elasticsearch)