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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值