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

教程列表

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


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

一、版本信息

Springboot 2.0.9.RELEASE

transport 5.6.16

Elasticsearch 5.6.16

二、Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.9.RELEASE</version> <!-- 该版本兼容Elasticsearch 5.6.16 -->
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.rkyao</groupId>
	<artifactId>spring-boot-elasticsearch-transport</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-elasticsearch-transport</name>
	<description>Demo project for Spring Boot</description>

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

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- elasticsearch依赖 -->
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>transport</artifactId>
			<version>5.6.16</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.7</version>
		</dependency>

		<!-- Lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</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());
    }

}
四、工程目录结构

在这里插入图片描述

五、参考文档

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
elasticsearch-rest-client-6.4.3.jar 一直冲突可能有几个原因。 首先,可能是由于版本兼容性问题导致冲突。elasticsearch-rest-client-6.4.3.jar 是 Elasticsearch 的 REST 客户端,如果您的 Elasticsearch 版本与此客户端不兼容,可能会导致冲突。您可以尝试更新 Elasticsearch 或使用与您当前 Elasticsearch 版本兼容的 REST 客户端。 其次,冲突可能是由于您的项目中存在多个版本的 elasticsearch-rest-client-6.4.3.jar。当存在多个相同的 JAR 文件但版本不同的情况下,可能会发生冲突。您可以检查项目的依赖关系,确保只引入一个版本的 elasticsearch-rest-client-6.4.3.jar。 另外,冲突可能是由于其他依赖项与 elasticsearch-rest-client-6.4.3.jar 冲突。在一些情况下,某些依赖项可能需要特定版本的 JAR 文件,并且与 elasticsearch-rest-client-6.4.3.jar 的版本冲突。您可以检查项目的所有依赖项,并确保它们与 elasticsearch-rest-client-6.4.3.jar 的版本兼容。 最后,冲突可能是由于项目中存在其他冲突的依赖项引起的。当项目中存在多个依赖项,它们之间存在冲突时,可能会导致冲突。您可以使用 Maven 或 Gradle 等构建工具来分析项目的依赖关系,并解决任何冲突。 总之,elasticsearch-rest-client-6.4.3.jar 一直冲突可能是由于版本兼容性问题、多个 JAR 文件的存在、与其他依赖项的冲突或其他原因引起的。您可以通过检查兼容性、解决版本冲突、检查依赖项并解决冲突等方式来解决这个问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值