前提是我们elasticsearch 服务已经集成了IK分词,具体集成下载对应的elasticsearch IK分词插件,在es插件包下创建IK文件夹,将下载好的IK包上传上去解压后重启es
1、pom引入
2、配置config类
@Configuration
public class RestClientConfig {
@Value("${elasticsearch.ip}")
private String ip;
@Bean
public ElasticsearchClient elasticsearchClient() {
ElasticsearchClient client;
// Create the low-level client
RestClient restClient = RestClient.builder(this.getElasticSearchHttpHosts()).build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
// And create the API client
client = new ElasticsearchClient(transport);
return client;
}
/**
* ElasticSearch 连接地址
* 多个逗号分隔
* 示例:127.0.0.1:9201,127.0.0.1:9202,127.0.0.1:9203
*/
private HttpHost[] getElasticSearchHttpHosts() {
String[] hosts = ip.split(",");
HttpHost[] httpHosts = new HttpHost[hosts.length];
for (int i = 0; i < httpHosts.length; i++) {
String host = hosts[i];
httpHosts[i] = new HttpHost(host.split(":")[0], Integer.parseInt(host.split(":")[1]));
}
return httpHosts;
}
}
3、创建service
/**
-
自定义es查询接口
/
public interface IBizElasticsearchService{ *
/- 判断索引是否存在
- @param index 索引
- @return boolean
*/
public boolean existsIndex(String index);
/**
- 创建索引
- @param index 索引
- @param aliasename aliasename
- @return boolean
*/
public boolean createIndex(String index, String aliasename, int numOfShards, Map<String, Property> properties);
/**
- 删除索引
- @param indexList indexList
- @return boolean
*/
public boolean deleteIndex(ListindexList);
/**
- 判断文档是否存在
- @param index index
- @param id id
- @return boolean
*/
public boolean existsDocument(String index, String id, Classclazz);
/**
- 保存文档
- 如果文档存在则更新文档
- @param index index
- @param id id
- @param qa qa
- @return IndexResponse
*/
public IndexResponse saveOrUpdateDocument(String index, String id, T qa);
/**
- 不指定IO保存文档
- @param index 索引
- @param qa 数据
- @return IndexResponse
*/
public IndexResponse saveOrUpdateDocument(String index, T qa);
/**
- 根据id获取文档
- @param index index
- @param id id
- @param clazz clazz
- @return T
*/
public T getById(String index, String id, Classclazz);
/**
- 根据id列表获取文档
- @param index index
- @param idList id
- @param clazz clazz
- @return List
*/
public ListgetByIdList(String index, List idList, Class clazz);
/**
- 分页查询
- @param index index
- @param pageNo pageNo
- @param pageSize pageSize
- @param clazz clazz
- @return HitsMetadata
*/
public HitsMetadatasearchByPages(String index, Integer pageNo, Integer pageSize, Class clazz, SearchRequest searchRequest);
/**
- 根据id删除文档
- @param id id
*/
public boolean deleteById(String index, String id);
/**
- 查询list
- @param clazz
- @param searchRequest
- @return
*/
HitsMetadatasearchList(Class clazz, SearchRequest searchRequest);
}
4、serviceImpl
@Service
@Slf4j
public class BizElasticsearchServiceImpl
@Autowired
private ElasticsearchClient client;
@Autowired
public void setClient(ElasticsearchClient client) {
this.client = client;
}
public boolean existsIndex(String index) {
try {
ExistsRequest existsRequest = new ExistsRequest.Builder().index(index).build();
BooleanResponse response = client.indices().exists(existsRequest);
return response.value();
} catch (IOException e) {
log.error("There is an error while getting index", e);
}
return false;
}
@Override
public boolean createIndex(String indexName, String aliasesName, int numOfShards, Map<String, Property> properties) {
try {
TypeMapping typeMapping = new TypeMapping.Builder().properties(properties).build();
// 我这里需要用到ik分词器,所以setting就写死了
IndexSettings indexSettings = new IndexSettings.Builder().numberOfShards(String.valueOf(numOfShards))
.analysis(q->q.analyzer("ik_max_tokenizer",q1->q1.custom(a->a.tokenizer("ik_max_word")))).build();
CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
.index(indexName)
.aliases(aliasesName, new Alias.Builder().isWriteIndex(true).build())
.mappings(typeMapping)
.settings(indexSettings)
.build();
CreateIndexResponse response = client.indices().create(createIndexRequest);
return response.acknowledged();
} catch (IOException e) {
log.error("There is an error while creating index", e);
}
return false;
}
@Override
public boolean deleteIndex(List<String> indexList) {
try {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(indexList).build();
DeleteIndexResponse response = client.indices().delete(deleteIndexRequest);
return response.acknowledged();
} catch (IOException e) {
log.error("There is an error while deleting index", e);
}
return false;
}
@Override
public boolean existsDocument(String index, String id, Class<T> clazz) {
try {
GetRequest getRequest = new GetRequest.Builder().index(index).id(id).build();
GetResponse<T> getResponse = client.get(getRequest, clazz);
return getResponse.found();
} catch (IOException e) {
log.error("There is an error while judging if the document exists", e);
}
return false;
}
@Override
public IndexResponse saveOrUpdateDocument(String index, String id, T t) {
try {
IndexRequest<T> indexRequest = new IndexRequest.Builder<T>().index(index).id(id).document(t).build();
return client.index(indexRequest);
} catch (IOException e) {
log.error("There is an error while saving the document", e);
}
return null;
}
@Override
public IndexResponse saveOrUpdateDocument(String index, T t) {
try {
IndexRequest<T> indexRequest = new IndexRequest.Builder<T>().index(index).document(t).build();
return client.index(indexRequest);
} catch (IOException e) {
log.error("There is an error while saving the document", e);
}
return null;
}
@Override
public T getById(String index, String id, Class<T> clazz) {
try {
GetRequest getRequest = new GetRequest.Builder().index(index).id(id).build();
GetResponse<T> getResponse = client.get(getRequest, clazz);
return getResponse.source();
} catch (IOException e) {
log.error("There is an error while getting the document", e);
}
return null;
}
@Override
public List<T> getByIdList(String index, List<String> idList, Class<T> clazz) {
try {
List<T> tList = new ArrayList<>(idList.size());
for (String id : idList) {
tList.add(client.get(new GetRequest.Builder().index(index).id(id).build(), clazz).source());
}
return tList;
} catch (IOException e) {
log.error("There is an error while getting the document list", e);
}
return null;
}
@Override
public HitsMetadata<T> searchByPages(String index, Integer pageNo, Integer pageSize, Class<T> clazz,SearchRequest searchRequest) {
try {
SearchResponse<T> searchResponse = client.search(searchRequest, clazz);
return searchResponse.hits();
} catch (IOException e) {
log.error("There is an error while searching by pages", e);
}
return null;
}
@Override
public HitsMetadata<T> searchList(Class<T> clazz,SearchRequest searchRequest) {
try {
SearchResponse<T> searchResponse = client.search(searchRequest, clazz);
return searchResponse.hits();
} catch (IOException e) {
log.error("There is an error while searching by list", e);
}
return null;
}
public boolean deleteById(String index, String id) {
try {
DeleteRequest deleteRequest = new DeleteRequest.Builder().index(index).id(id).build();
DeleteResponse deleteResponse = client.delete(deleteRequest);
return "deleted".equals(deleteResponse.result().jsonValue());
} catch (IOException e) {
log.error("There is an error while deleting id document", e);
}
return false;
}
}
这里主要讲下我们对那些字段分词,我们调用createIndex,传入Map<String, Property> properties,如下是我们对title和content字段进行IK分词:
Map<String,Property> map = new HashMap<>();
Property titleProperty = Property.of(pBuilder -> pBuilder.text(tBuilder -> tBuilder.analyzer("ik_max_word").searchAnalyzer("ik_max_word")));
map.put("title",titleProperty);
Property contentProperty = Property.of(pBuilder -> pBuilder.text(tBuilder -> tBuilder.analyzer("ik_max_word").searchAnalyzer("ik_max_word")));
map.put("content",contentProperty);
return R.data(bizElasticsearchService.createIndex(indexName,indexName+"_aliases",2,map));