1.JAVA連接ES

配置如下
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>com.qf</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- 1.elastic的jar包
2.es高級api
3.junit
4.lombok-->
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
</dependencies>
</project>

package com.qf.utils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
public class ESClient {
public static RestHighLevelClient getClient(){
HttpHost httpHost=new HttpHost("192.128.64.128",9200);
RestClientBuilder clientBuilder= RestClient.builder(httpHost);
RestHighLevelClient client=new RestHighLevelClient(clientBuilder);
return client;
}
}
創建Demo1來測試連接
package com.qf.test;
import com.qf.utils.ESClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Test;
public class Demo1 {
@Test
public void testConnect() {
try {
RestHighLevelClient client = ESClient.getClient();
System.out.println("ok!");
} catch (Exception e) {
System.out.println(e);
}
}
}
2.Java創建索引
注意:由於之前使用的Liunx版本問題,在運行版本的時候提示java.net.ConnectException: Timeout connecting to xxxx.9200在網上找了很多辦法無法解決,最后實在沒辦法就下載了Windows版本就可以了。
package com.qf.test;
import com.qf.utils.ESClient;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.client.indices.CreateIndexRequest;
//import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.junit.Test;
import java.io.IOException;
public class Demo2 {
String index="person";
String type="man";
@Test
public void createIndex() throws IOException {
//1.索引的settings
Settings.Builder settings = Settings.builder()
.put("number_of_shards", 3)
.put("number_of_replicas", 1);
//2.索引的mappings
XContentBuilder mappings = JsonXContent.contentBuilder();
mappings .startObject()
.startObject("properties")
.startObject("name")
.field("type", "text")
.endObject()
.startObject("age")
.field("type", "integer")
.endObject()
.startObject("birthday")
.field("type", "date")
.field("format", "yyyy-MM-dd")
.endObject()
.endObject()
.endObject();
//將settings和Mappings 封裝到一個Request對象
CreateIndexRequest request = new CreateIndexRequest(index)
.settings(settings)
.mapping(type, mappings);
//通過Client對象連接ES並執行創建索引
RestHighLevelClient client = ESClient.getClient();
CreateIndexResponse createIndexResponse =client.indices().create(request,RequestOptions.DEFAULT);
System.out.println("resp:" + createIndexResponse.toString());
}
}
2.1Java查詢刪除索引
@Test
public void delete() throws IOException {
//1.准備request對象
DeleteIndexRequest request=new DeleteIndexRequest();
request.indices(index);
//2.通過Cilent操作
RestHighLevelClient client = ESClient.getClient();
AcknowledgedResponse delete=client.indices().delete(request,RequestOptions.DEFAULT);
/* 3.輸出 */
System.out.println(delete);
}
@Test
public void exists() throws IOException {
//1.准備request對象
GetIndexRequest request=new GetIndexRequest();
request.indices(index);
//2.通過Cilent操作
RestHighLevelClient client = ESClient.getClient();
boolean exists= client.indices().exists(request,RequestOptions.DEFAULT);
//3.輸出
System.out.println(exists);
}
2.2Java操作文檔
2.2.1添加文檔
1.創建Person類
package com.qf.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
public class Person {
@JsonIgnore
private Integer id;
private String name;
private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
public Person(Integer id, String name, Integer age, Date birthday) {
this.id = id;
this.name = name;
this.age = age;
this.birthday = birthday;
}
public Integer getId() {
return id;
}
}
2.創建測試類Demo3
注:添加json依賴包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
package com.qf.test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.qf.entity.Person; import com.qf.utils.ESClient; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.junit.Test; import java.io.IOException; import java.util.Date; public class Demo3 { String index="person"; String type="man"; RestHighLevelClient client = ESClient.getClient(); ObjectMapper mapper=new ObjectMapper(); @Test public void createDoc() throws IOException { //1.准備一個json數據 Person person=new Person(1,"張三",20,new Date()); String json= mapper.writeValueAsString(person); //2.准備一個request對象(手動指定id) IndexRequest request=new IndexRequest(index,type,person.getId().toString()); request.source(json, XContentType.JSON); //3.通過client對象執行添加 IndexResponse resp =client.index(request, RequestOptions.DEFAULT); //4.輸出返回結果 System.out.println(resp.getResult().toString()); } }
2.2.2修改文檔
@Test
public void update() throws IOException {
//創建Map修改指定內容
Map<String,Object>doc= new HashMap<String, Object>();
doc.put("name","張大三");
String docID="1";
UpdateRequest request=new UpdateRequest(index,type,docID);
request.doc(doc);
UpdateResponse update=client.update(request,RequestOptions.DEFAULT);
System.out.println(update.getResult().toString());
}
2.2.3刪除文檔
@Test
public void delete() throws IOException {
DeleteRequest request=new DeleteRequest(index,type,"1");
DeleteResponse resp=client.delete(request,RequestOptions.DEFAULT);
System.out.println(resp.getResult().toString());
}
2.2.4批量添加文檔
@Test
public void BulkDoc() throws IOException {
Person p1= new Person(1,"HJH",20,new Date());
Person p2= new Person(2,"YQG",30,new Date());
Person p3= new Person(3,"LWD",22,new Date());
String json1= mapper.writeValueAsString(p1);
String json2= mapper.writeValueAsString(p2);
String json3= mapper.writeValueAsString(p3);
//創建Request,將准備好的數據封裝進去
BulkRequest request=new BulkRequest();
request.add(new IndexRequest(index,type,p1.getId().toString()).source(json1,XContentType.JSON));
request.add(new IndexRequest(index,type,p2.getId().toString()).source(json1,XContentType.JSON));
request.add(new IndexRequest(index,type,p3.getId().toString()).source(json1,XContentType.JSON));
BulkResponse resp=client.bulk(request,RequestOptions.DEFAULT);
System.out.println(resp.toString());
}
2.2.4批量刪除文檔
@Test public void bulkDeleteDoc() throws IOException { BulkRequest request=new BulkRequest(); request.add(new DeleteRequest(index,type,"1")); request.add(new DeleteRequest(index,type,"2")); request.add(new DeleteRequest(index,type,"3")); BulkResponse resp=client.bulk(request,RequestOptions.DEFAULT); System.out.println(resp); }
