栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Elasticsearch7.17.0新版本的JavaApi使用

Elasticsearch7.17.0新版本的JavaApi使用

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

maven依赖:


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.3
         
    
    ljxwtl.cn
    SpringBoot
    0.0.1-SNAPSHOT
    SpringBoot
    SpringBoot
    
        1.8
    
    
        
        
            org.springframework.boot
            spring-boot-starter-web
            
            
                
                    org.springframework.boot
                    spring-boot-starter-tomcat
                
            
        
        
            org.springframework.boot
            spring-boot-starter-undertow
        

        
            org.projectlombok
            lombok
            true
        

        
        
            co.elastic.clients
            elasticsearch-java
            7.17.0
        
        
            jakarta.json
            jakarta.json-api
            2.0.1
        
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            junit
            junit
            4.13.2
            test
        


        
        
            com.alibaba
            fastjson
            1.2.79
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    


测试用的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 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 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 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 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 personIndexRequest = new IndexRequest.Builder().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 personPersonUpdateRequest = new UpdateRequest.Builder().index("person").id("4").doc(person).build();

        UpdateResponse 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 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 personSearchResponse = elasticsearchClient.search(searchRequest, Person.class);
        List> 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 personSearchResponse = elasticsearchClient.search(searchRequest, Person.class);
        List> hits = personSearchResponse.hits().hits();
        hits.forEach(hit ->{
            System.out.println(hit.source());
        });
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/748196.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号