添加Springboot项目中pom文件ES依赖
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.5.1</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- es client依赖 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.5.1</version>
</dependency>
配置ik分词器
- 下载(https://github.com/medcl/elasticsearch-analysis-ik/releases)分词器,查询与ES版本对应的IK分词器版本。(我才用zip包)
- 把解压后的ik文件夹,复制到ES服务所在的位置,目录位置为/elasticsearch/plugins/ik,如果没有ik文件夹则创建
- 重启es服务后,看到ik分词器已经启用
添加Java REST Client 客户端配置文件
/**
* Es配置类,提供client连接
*
* @author yz
* @date 2018/12/06
*/
@Configuration
public class EsConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.schema}")
private String schema;
@Value("${elasticsearch.connectionRequestTimeOut}")
private int connectTimeOut;
@Value("${elasticsearch.socketTimeOut}")
private int socketTimeOut;
@Value("${elasticsearch.connectionRequestTimeOut}")
private int connectionRequestTimeOut;
@Value("${elasticsearch.maxConnectNum}")
private int maxConnectNum;
@Value("${elasticsearch.maxConnectPerRoute}")
private int maxConnectPerRoute;
@Value("${elasticsearch.uniqueConnectTimeConfig}")
private boolean uniqueConnectTimeConfig;
@Value("${elasticsearch.uniqueConnectNumConfig}")
private boolean uniqueConnectNumConfig;
private RestClientBuilder builder;
private RestHighLevelClient client;
/**
* 注入client连接Bean
*
* @return transportClient
*/
@Bean
public RestHighLevelClient restHighLevelClient() {
HttpHost httpHost = new HttpHost(host, port, schema);
builder = RestClient.builder(httpHost);
if (uniqueConnectTimeConfig) {
setConnectTimeOutConfig();
}
if (uniqueConnectNumConfig) {
setMutiConnectConfig();
}
client = new RestHighLevelClient(builder);
return client;
}
/**
* 主要关于异步httpclient的连接延时配置
*/
public void setConnectTimeOutConfig() {
builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
requestConfigBuilder.setConnectTimeout(connectTimeOut);
requestConfigBuilder.setSocketTimeout(socketTimeOut);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
return requestConfigBuilder;
}
});
}
/**
* 主要关于异步httpclient的连接数配置
*/
public void setMutiConnectConfig() {
builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setMaxConnTotal(maxConnectNum);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
return httpClientBuilder;
}
});
}
Java REST Client分词器的使用
-
设置索引mapping
/**
* mapping过滤条件设置工具类
*
* @author yz
* @date 2018/12/10
*/
public class Mapping {
/**
* 分词器设置拼接工具
* @return XContentBuilder
*/
public static XContentBuilder getSObjectMapping(){
XContentBuilder builder = null;
try {
builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("name");
{
builder.field("type", "text");
builder.field("analyzer", "ik_max_word");
}
builder.endObject();
builder.startObject("userNikckName");
{
builder.field("type", "text");
builder.field("analyzer", "ik_max_word");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return builder;
}
-
生成索引
/**
* 设置分词器
*
* @param index
* @param type
* @return boolean
* @Excpiton Exception
*/
@Override
public boolean setMapping(String index, String type) throws Exception{
CreateIndexRequest indexRequest = new CreateIndexRequest(index, Settings.builder().build());
client.indices().create(indexRequest,RequestOptions.DEFAULT);
PutMappingRequest request = new PutMappingRequest(index);
request.type(type);
//创建mapping,设置分词器
request.source(Mapping.getSObjectMapping());
AcknowledgedResponse acknowledgedResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
return acknowledgedResponse.isAcknowledged();
}
- 对应用字段采用分词器并进行全文搜索
/**
* 全文搜索
*
* @param filter
* @return List<SearchHit>
* @Excpiton Exception
*/
@Override
public List<SearchHit> query(Esfilter filter) {
MultiSearchResponse sr = null;
//复合查询
MultiSearchRequest request = new MultiSearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
List<SearchHit> list = new ArrayList<>();
if (filter.getKeyWord() == null){
return list;
}
//复合查询
SearchRequest firstSearchRequest = new SearchRequest();
//bool复合条件查询,should相当于or
searchSourceBuilder.query(QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery("name", filter.getKeyWord()).analyzer("ik_max_word"))//对指定字段设置ik分词器
.should(QueryBuilders.matchQuery("userNickName", filter.getKeyWord()).analyzer("ik_max_word"))
).from((filter.getPageNum() - 1) * filter.getPageSize())//设置分页
.size(filter.getPageSize());
firstSearchRequest.source(searchSourceBuilder);
request.add(firstSearchRequest);
try {
sr = client.msearch(request, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
//hit对象结果集
for (MultiSearchResponse.Item item : sr.getResponses()) {
SearchResponse response = item.getResponse();
SearchHits hits = response.getHits();
for (SearchHit hit: hits){
list.add(hit);
}
System.out.println(response.getHits().getTotalHits());
}
return list;
}