ES通用dao
@Slf4j
@Service
public class ElasticSearchDAO {
@Autowired
private RestHighLevelClient client;
/**
* 判断索引是否存在
* @param indexName
* @return
* @throws IOException
*/
public boolean existsIndex(String indexName) throws IOException {
GetIndexRequest request = new GetIndexRequest(indexName);
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
log.info("{} exists:{}",indexName,exists);
return exists;
}
/**
* 创建索引
* @param indexName
* @throws IOException
*/
public void createIndex(String indexName) throws IOException {
CreateIndexRequest createRequest = new CreateIndexRequest(indexName);
CreateIndexResponse response = client.indices().create(createRequest, RequestOptions.DEFAULT);
log.info("{}创建成功 {}",indexName, JSON.toJSON(response));
}
/**
* 删除索引
* @param indexName
* @throws IOException
*/
public void deleteIndex(String indexName) throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
log.info("{}删除成功 {}",indexName, JSON.toJSON(response));
}
/**
* 批量插入数据
*/
public void insertBatch(String indexName, List<ElasticEntity> list) throws IOException {
BulkRequest request = new BulkRequest();
list.forEach(item -> request.add(new IndexRequest(indexName).id(item.getId())
.source(JSONUtil.toJSON(item.getData()), XContentType.JSON)));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
log.info("{}批量插入数据成功 {}",indexName, JSON.toJSON(response));
}
/**
* 添加或更新数据
*/
public void saveOrUpdate(String indexName,ElasticEntity entity) throws IOException {
IndexRequest request = new IndexRequest(indexName);
request.id(entity.getId());
request.source(JSONUtil.toJSON(entity.getData()), XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
log.info("{}添加或更新数据成功 {}",indexName, JSON.toJSON(response));
}
/**
* 通过id批量删除
*/
public <T> void deleteBatch(String indexName, Collection<T> idList) throws IOException {
BulkRequest request = new BulkRequest();
idList.forEach(item -> request.add(new DeleteRequest(indexName, item.toString())));
BulkResponse response = client.bulk(re