Bootstrap

spring boot 集成elasticsearch 创建mapping

版本说明

  • Spring Boot 版本:2.6.1
  • elasticsearch 版本:7.15.2

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

连接地址配置

es.host=127.0.0.1
es.port=9200

注入bean

@Configuration
public class ElasticsearchConfiguration {

    @Value("${es.host}")
    private String host;
    @Value("${es.port}")
    private int port;

    @Bean(value = "highLevelClient", destroyMethod = "close")
    public RestHighLevelClient initHighLevelClient() {
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, port, "http")));
    }
}

mapping配置,mapping.json文件

{
  "properties": {
    "username": {
      "type": "keyword"
    },
    "password": {
      "type": "keyword"
    }
  }
}

创建mapping

@Component
public class ElasticsearchInitialize {

    private static Logger log = LoggerFactory.getLogger(ElasticsearchInitialize.class);

    @Autowired
    private RestHighLevelClient highLevelClient;

    public static final String projectDataIndex = "index_to_user";

    @PostConstruct
    public void initEsMetadata() {
        try {

            GetIndexRequest getIndexRequest = new GetIndexRequest(projectDataIndex);

            // 判断索引是否存在
            if(!highLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT)) {

                File file = ResourceUtils.getFile("classpath:json/mapping.json");

                // 读取mapping配置
                String jsonStr = IOUtils.toString(file.toURI(), StandardCharsets.UTF_8);

                CreateIndexRequest request = new CreateIndexRequest(projectDataIndex);

                XContentBuilder builder = XContentFactory.jsonBuilder().map(JSONObject.parseObject(jsonStr));

                request.mapping(builder);

                highLevelClient.indices().create(request, RequestOptions.DEFAULT);
            }

            // 测试添加数据
            addTestData();

        } catch (Exception e) {
            log.error("init es metadata error:", e);
        }
    }

    /**
     * 测试添加数据
     */
    private void addTestData() {

        IndexRequest request = new IndexRequest(ElasticsearchInitialize.projectDataIndex);

        Map<String, String> data = new HashMap<>();

        data.put("username", "张三");

        data.put("password", "123");

        request.source(data, XContentType.JSON);

        try {

            IndexResponse indexResponse = highLevelClient.index(request, RequestOptions.DEFAULT);

            System.out.println(indexResponse.status());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如果要使用elasticsearch-head的需要在elasticsearch安装目录下修改config/elasticsearch.yml文件

http.cors.enabled: true
http.cors.allow-origin: "*"
# 放弃安全验证
xpack.security.enabled: false
;