Elasticsearch:运⽤Java创建索引并写⼊数据
在我之前的⽂章 “”,我讲述了如何在 Java 应⽤中创建⼀个索引,并写⼊数据。在今天的例⼦中,我来着重讲述如何有⽬的地创建按照我们需求的索引,并介绍⼏种常见的⽅法写⼊数据。
安装
我们⾸先参考如下的⽂章来安装我们需要的 Elasticsearch 及 Kibana:
此外,针对 Elastic Stack 7.15 及以后的版本,强烈建议对 Elasticsearch 进⾏安全配置。你可以参考⽂章 “”。我的 Elasticsearch 集的超级⽤户 elastic 的密码为 password。
创建 Java 应⽤
我们⽤⾃⼰喜欢的 IDE 创建⼀个 Java 应⽤。在本例中,我将创建⼀个 Maven 应⽤:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.liuxg</groupId>
<artifactId>Elasticsearch-Java</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elastic.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>${elastic.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elastic.version}</version>
</dependency>
<dependency>
<groupId>com.</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
</dependencies>
<properties>
<mavenpiler.source>8</mavenpiler.source>
<mavenpiler.target>8</mavenpiler.target>
<elastic.version>7.15.0</elastic.version>
</properties>
</project>
在上⾯,我们创建⼀个叫做 ElasticsearchJava 的 class:
ElasticsearchJava.java
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
public class ElasticsearchJava {
private static RestHighLevelClient client = null;
private static synchronized RestHighLevelClient makeConnection() {
final BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider
.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "password"));
if (client == null) {
client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
}
})
);
}
return client;
}
public static void main(String[] args) {
client = makeConnection();
}
}
在上⾯,我们创建了⼀个和 Elasticsearch 的连接。请注意我们使⽤了超级⽤户 elastic 极其密码。如果我们没有为我们的集设置密码的话,我们其实可以⾮常简单地使⽤如下的代码来进⾏连接:
private static synchronized RestHighLevelClient makeConnection() {
if(client == null) {
restHighLevelClient = new RestHighLevelClient(
RestClient.builder( new HttpHost("localhost", "9200", "http")));
}
return client;
}
接下来,我们参照 Elastic 官⽅⽂档 “”,我们使⽤如下的代码:
CreateIndexRequest request = new CreateIndexRequest("employees");
request.settings(Settings.builder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println("response id: " + createIndexResponse.index());
}
}
在上⾯,我们建⽴⼀个连接,并创建⼀个叫做 employees 的索引。请注意在索引的名字中,我们不可以有⼤写字母,否则会导致错误。在上⾯,我们设置 number_of_shards 为1, number_of_replicas
为0。上⾯代码的输出为:
response id: employees
我们可以使⽤ Kibana 来检查我们的结果:
从上⾯的结果中,我们可以看出来 employees 索引已经被成功地创建。
也许你对创建⼀个索引的 mapping 也感兴趣,那么你可以使⽤如下的代码来实现:
String mappings = "{\n" +
"  \"properties\": {\n" +
"    \"id\": {\n" +
"      \"type\": \"keyword\"\n" +
java中index是什么意思
"    },\n" +
"    \"name\": {\n" +
"      \"type\": \"text\"\n" +
"    }\n" +                "  }\n" +
"}";
System.out.println("mapping is as follows: ");
System.out.println(mappings);
try {
CreateIndexRequest request = new CreateIndexRequest("employees");
request.settings(Settings.builder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
);
request.mapping(mappings, XContentType.JSON);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);            System.out.println("response id: " + createIndexResponse.index());
} catch (Exception e) {
//            e.printStackTrace();
}
}
上⾯代码运⾏的结果为:
mapping is as follows:
{
"properties": {
"id": {
"type": "keyword"
},
"name": {
"type": "text"
}
}
}
response id: employees
我们可以在 Kibana 中进⾏查看:
GET employees/_mapping
上⾯命令的结果为:
{
"employees" : {
"mappings" : {
"properties" : {
"id" : {
"type" : "keyword"
},
"name" : {
"type" : "text"
}
}
}
}
}
上⾯的代码类似于 Kibana 中如下的命令:
PUT employees
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
},
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"name": {
"type": "text"
}
}
}
}
上⾯的命令创建⼀个叫做 employees 的索引,并对它进⾏设置和定义 mappings。
接下来,我们参照另外⼀个⽂档 “” 来对已经创建的索引进⾏写⼊操作:
// Write documents into employees index
IndexRequest request = new IndexRequest("employees");
request.id("1");
String jsonString = "{" +
"\"id\":\"1\"," +
"\"name\":\"liuxg\"" +
"}";
request.source(jsonString, XContentType.JSON);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
System.out.println("response id: "+Id());
System.out.println("response name: "+Result().name());
上⾯的代码想已经创建的 employees 索引写⼊⽂档。其中的⽂档时以 JSON 形式写⼊的。当然如果我
们之前没有创建 employees 这个索引,上⾯的 API 也将会⾃动帮我们⽣成 employees 这个索引,并把相应的⽂档写⼊。当然这个索引的 settings 及 mappings 也许不是我们想要的,⽽是系统按照默认的⽅式给出的。
上⾯的命令类似于在 Kibana 中的如下的命令:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。