Elasticsearch7.18.1新版本的JavaApi使用

本文介绍了Elasticsearch7.16版本后废弃High-levelAPI,转向Low-LevelAPI的变化。主要内容包括如何在Java项目中集成新API,如创建索引、获取映射和设置、数据操作等示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

新的api官网教程如下链接:

Elasticsearch Java API Client [8.2] | Elastichttps://www.elastic.co/guide/en/elasticsearch/client/java-api-client/8.2/index.html

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>8.1.1</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;  import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor; package ljxwtl;
 
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String id;
    private String name;
    private Integer age;
    private String sex;
    private String tel;
}

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

测试类:

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());
        });
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值