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());
});
}
}
|