zhongrj
2024-04-09 66b6525861e566adb3db8f06f824de7751fbca9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package org.springblade.es.service;
 
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.json.JsonXContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
 
@Service
public class ElasticsearchIndexService {
 
    @Autowired
    private RestHighLevelClient client;
 
    public void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("your_index");
 
        XContentBuilder builder = JsonXContent.contentBuilder()
            .startObject()
            .startObject("properties")
            .startObject("field1").field("type", "text").endObject()
            .startObject("field2").field("type", "text").endObject()
            // ... 定义其他字段
            .endObject()
            .endObject();
 
        request.mapping("_doc", builder);
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
    }
}