创建索引模版
number_of_shards表示分片数 number_of_replicas 表示副本数 aliases表示以改模版创建的索引别名
PUT _template/user_action_log_template
{
"index_patterns": ["user_action_log_*"],
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
},
"aliases": {
"user_action_log": {}
},
"mappings": {
"_source": {
"enabled": true
},
"properties": {
"timestamp": {
"type": "date"
},
"action": {
"type": "text"
},
"user_id": {
"type": "keyword"
}
}
}
}
创建索引,符合user_action_log_*规则 则使用模版创建
PUT user_action_log_202305191657
获取索引结构
GET /user_action_log_202305191657/_mapping
查看模版创建了多少索引
GET /_cat/indices/user_action_log_*
插入
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1",9200))
);
for (int i = 0; i < 10; i++) {
IndexRequest request = new IndexRequest();
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
String currentDate = dateFormat.format(date);
request.index("user_action_log_" + currentDate).id(System.currentTimeMillis() + "");
UserActionLogDoc userActionLogDoc = new UserActionLogDoc(new Timestamp(System.currentTimeMillis()), "测试" + currentDate, UUID.randomUUID().toString());
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(userActionLogDoc);
request.source(userJson, XContentType.JSON);
esClient.index(request, RequestOptions.DEFAULT);
}
esClient.close();
查询
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1",9200))
);
SearchRequest request = new SearchRequest();
request.indices("user_action_log");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("action","测试"));
searchSourceBuilder.from(0);
searchSourceBuilder.size(100);
request.source(searchSourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits){
System.out.println(hit.getSourceAsString());
}
esClient.close();