IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> Elasticsearch7.17.0新版本的JavaApi使用 -> 正文阅读

[大数据]Elasticsearch7.17.0新版本的JavaApi使用

Elasticsearch升级到7.16之后,已经废弃了High-level API了,统一使用Low-Level API,所以某些接口发生了变化,下面将会列出Elasticsearch Low-Level API的一些基本操作。

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.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ljxwtl.cn</groupId>
    <artifactId>SpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot</name>
    <description>SpringBoot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--  springboot 整合web组件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 从依赖信息里移除 Tomcat配置 -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--elasticsearch依赖包开始-->
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>7.17.0</version>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--elasticsearch依赖包结束-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>


        <!-- json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.79</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

测试用的Entity:

package ljxwtl.entity;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String id;
    private String nickname;
    private String name;
    private Integer age;
    private Boolean sex;
}

这里建议使用基本类型的包装类,因为基本类型是有默认值的,所以会影响更新结果。?

测试类:

package ljxwtl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.*;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.alibaba.fastjson.JSON;
import ljxwtl.entity.Person;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.IOException;
import java.util.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootApplicationMain.class)
public class ApplicationTests {

    private ElasticsearchClient elasticsearchClient;

    @Before
    public void before(){
        RestClient restClient = RestClient.builder(
                new HttpHost("ljxwtl.cn", 9200)
        )
                .setHttpClientConfigCallback(httpAsyncClientBuilder->{
                    //账密设置
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    //es账号密码(一般使用,用户elastic)
                    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456"));
                    httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

                    return httpAsyncClientBuilder;
                }).build();

        RestClientTransport restClientTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());


        elasticsearchClient = new ElasticsearchClient(restClientTransport);
    }


    @Test
    public void createIndex() throws IOException {
        String indexName = "es_index_name";
        String aliasIndexName = "es_alias_index_name";

        Map<String, Property> propertyMap = new HashMap<>();
        propertyMap.put("name",new Property(new TextProperty.Builder().index(true).store(true).build()));
        propertyMap.put("age",new Property(new IntegerNumberProperty.Builder().index(false).build()));
        propertyMap.put("sex",new Property(new BooleanProperty.Builder().index(false).build()));

        TypeMapping typeMapping = new TypeMapping.Builder().properties(propertyMap).build();
        IndexSettings indexSettings = new IndexSettings.Builder().numberOfShards(String.valueOf(1)).numberOfReplicas(String.valueOf(0)).build();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                .index(indexName)
                .aliases(aliasIndexName, new Alias.Builder().isWriteIndex(true).build())
                .mappings(typeMapping)
                .settings(indexSettings)
                .build();

        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexRequest);
        System.out.println(createIndexResponse.acknowledged());
    }

    @Test
    public void getIndexWithMappingsAndSettings() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest.Builder().index("es_index_name").build();
        GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(getIndexRequest);

        IndexState es_index_name = getIndexResponse.get("es_index_name");

        System.out.println(JSON.toJSONString(es_index_name.mappings().properties()));
        System.out.println(JSON.toJSONString(es_index_name.aliases()));
        System.out.println(JSON.toJSONString(es_index_name.settings()));
    }


    @Test
    public void deleteIndex() throws IOException {
        List<String> indexList = Collections.singletonList("es_index_name");
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(indexList).build();
        DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(deleteIndexRequest);
        System.out.println(deleteIndexResponse.acknowledged());
    }

    @Test
    public void getESDataByIndexAndIdTest() throws Exception {
        GetRequest getRequest = new GetRequest.Builder().index("person").id("1").build();
        GetResponse<Person> personGetResponse = elasticsearchClient.get(getRequest, Person.class);
        Person person = personGetResponse.source();
        System.out.println(person);
    }

    @Test
    public void existsDocument() throws IOException {
        GetRequest getRequest = new GetRequest.Builder().index("person").id("4").build();
        GetResponse<Person> personGetResponse = elasticsearchClient.get(getRequest, Person.class);

        System.out.println(personGetResponse.source());
        System.out.println(personGetResponse.found());
    }

    @Test
    public void saveDocument() throws IOException {
        Person person = new Person();
        person.setNickname("小奇同学");
        person.setName("小奇");
        person.setAge(1);
        person.setSex(true);
        IndexRequest<Person> personIndexRequest = new IndexRequest.Builder<Person>().index("person").id("7").document(person).build();

        IndexResponse indexResponse = elasticsearchClient.index(personIndexRequest);

        //结果成功为:Created
        System.out.println(indexResponse.result());
    }

    @Test
    public void updateDocument() throws IOException {
        Person person = new Person();
//        person.setNickname("里斯kitty");
        person.setName("里斯1234");
//
//        person.setSex(true);
//        person.setAge(28);
//        person.setSex(true);
        UpdateRequest<Person, Person> personPersonUpdateRequest = new UpdateRequest.Builder<Person, Person>().index("person").id("4").doc(person).build();

        UpdateResponse<Person> personUpdateResponse = elasticsearchClient.update(personPersonUpdateRequest, Person.class);

        //结果成功为:Updated
        System.out.println(personUpdateResponse.result());
    }


    @Test
    public void getDocumentById() throws IOException {
        GetRequest getRequest = new GetRequest.Builder().index("person").id("7").build();

        GetResponse<Person> personGetResponse = elasticsearchClient.get(getRequest, Person.class);

        System.out.println(personGetResponse.source());
        System.out.println(personGetResponse.id());
    }

    @Test
    public void search() throws IOException {
        SearchRequest searchRequest = new SearchRequest.Builder().index("person").build();
        SearchResponse<Person> personSearchResponse = elasticsearchClient.search(searchRequest, Person.class);
        List<Hit<Person>> hits = personSearchResponse.hits().hits();
        hits.forEach(hit ->{
            System.out.println(hit.source());
        });
    }

    @Test
    public void searchByPages() throws IOException {
        SearchRequest searchRequest = new SearchRequest.Builder().index("person").from(0).size(10).build();
        SearchResponse<Person> personSearchResponse = elasticsearchClient.search(searchRequest, Person.class);
        List<Hit<Person>> hits = personSearchResponse.hits().hits();
        hits.forEach(hit ->{
            System.out.println(hit.source());
        });
    }
}
  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2022-02-28 15:36:32  更:2022-02-28 15:39:52 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 11:36:31-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码