前言 : 最近在看es,但是发现很少有从数据结构创建到应用的实例文章,所以决定自己写一个,共勉。
一 . 创建数据:
数据结构参考一下网站并稍加改动。
Elasticsearch 入门教程 - completion suggest实现搜索提示www.dczou.com1.因为测试数据中存在中文,所以第一步需要导入中文分词器 (ik分词器),在bin目录下执行以下命令,执行完成后重启es。
bin/elasticsearch-plugin install https:// github.com/medcl/elasti csearch-analysis-ik/releases/download/v6.5.3/elasticsearch-analysis-ik-6.5.3.zip
2 . 创建index(news_website),index的json结构格式如下。
{ "mappings": {
"news" : {
"properties" : {
"title" : {
"type": "text",
"analyzer": "ik_max_word",
"fields": {
"suggest" : {
"type" : "completion",
"analyzer": "ik_max_word"
}
}
},
"content": {
"type": "text",
"analyzer": "ik_max_word"
},
"core":{
"type":"double"
},
"group":{
"type":"text"
}
}
}
}
}
索引名称: news_website
索引Type: news
字段:title 标题,ik 细粒度分词,支持suggest推荐查询。
字段:content 详情
字段:core 详情
字段:group 分组
3.加入maven依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
4 . 创建客户端
public class InitClient {
public static RestHighLevelClient getClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200))
);
return client;
}
}
5.创建索引的API
try (RestHighLevelClient client = InitClient.getClient();) {
// 创建索引名
CreateIndexRequest request = new CreateIndexRequest("news_website");
String source = "{n" +
" "properties" : {n" +
" "title" : {n" +
" "type": "text",n" +
" "analyzer": "ik_max_word",n" +
&