赞
踩
ES提供索引新文档时自动自动新增索引的能力,但是由于其动态映射的结果可能不符合预期, 因此采用设置映射模板,通过索引名匹配进行映射设置。
PUT _template/template1 { "template": "repeater_replay_*", "settings": { "index.number_of_shards": 5, "number_of_replicas": 1 }, "mappings": { "_doc": { "properties": { "record_id": { "type": "keyword" }, "task_id": { "type": "keyword" }, "task_run_id": { "type": "keyword", "doc_values": true }, "app_id": { "type": "keyword" }, "app_name": { "type": "keyword" }, "environment": { "type": "keyword" }, "host": { "type": "keyword" }, "trace_id": { "type": "keyword" }, "status": { "type": "byte" }, "cost": { "type": "long" }, "diff_result": { "type": "text", "index": false }, "response": { "type": "text", "index": false }, "mock_invocation": { "type": "text", "index": false } } } } }
根据官网建议使用Rest High Level的client。为了防止被springboot父工程的项目覆盖,故采用重复依赖来解决。在选择client版本时需要注意,Rest High Level的版本需要和es服务器版本对应,至少大版本是要对应的。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.3.2</version>
</dependency>
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts));
IndexRequest request = new IndexRequest(realIndex, type).source(docSource, XContentType.JSON).timeout("1s").opType("index");
client.index(request);
SearchRequest searchRequest = new SearchRequest("index-*").preference("_local");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("price", 20)));
searchRequest.source(sourceBuilder);
client.search(searchRequest);
这种属于精确查询,请求体如下:
{
"query" : {
"constant_score" : {
"filter" : {
"term" : {
"price" : 20
}
}
}
}
}
已经学会设置索引模板设置,客户端也学会了如何编写,在后续使用过程中,如果有别的新的,再继续总结。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。