项目地址 : https://gitee.com/loving_jie/mufan/tree/master/search
1. 添加jar包坐标
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.2.1</version>
</dependency>
2.配置
elasticsearch:
host: 127.0.0.1
port: 9200
schedule: http
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.schedule}")
private String schedule;
@Bean
public RestHighLevelClient restHighLevelClient(){
RestClientBuilder builder = RestClient.builder(
new HttpHost(host, port,schedule)
);
return new RestHighLevelClient(builder);
}
}
3.springboot整合之索引创建 批量查询
import com.alibaba.fastjson.JSONObject;
import com.hj.common.constant.EsStatus;
import com.hj.common.exception.BusinessException;
import com.hj.common.util.StringUtils;
import com.hj.search.service.EsService;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Service
public class EsServiceImpl implements EsService {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String TYPE = "type";
@Autowired
private RestHighLevelClient client;
@Override
public boolean createIndex(String indexName, Integer shards, Integer replicas, Map<String, Map<String, String>> properties) {
if (existsIndex(indexName)) {
throw new BusinessException("该索引名称已存在");
}
CreateIndexRequest mufanIndex = new CreateIndexRequest(indexName);
mufanIndex.settings(Settings.builder()
.put("index.number_of_shards", shards)
.put("index.number_of_replicas", replicas)
);
if (!StringUtils.isEmpty(properties)) {
JSONObject sourceJson = new JSONObject();
sourceJson.put("properties", JSONObject.toJSON(properties));
mufanIndex.mapping(TYPE, sourceJson.toJSONString(), XContentType.JSON);
}
CreateIndexResponse response = null;
try {
response = client.indices().create(mufanIndex);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("索引创建失败");
}
return response.isAcknowledged();
}
@Override
public boolean deleteIndex(String indexName) {
if (!existsIndex(indexName)) {
throw new BusinessException("该索引名称不存在");
}
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
DeleteIndexResponse response = null;
try {
response = client.indices().delete(request);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("删除索引异常");
}
return response.isAcknowledged();
}
public boolean existsIndex(String esIndex) {
boolean exist = false;
try {
Response response = client.getLowLevelClient().performRequest("HEAD", esIndex);
exist = response.getStatusLine().getReasonPhrase().equals("OK");
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("校验失败");
}
return exist;
}
@Override
public Map<String, Object> insertDoc(String indexName, String type, String id, Object data) {
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(data);
IndexRequest indexRequest = new IndexRequest(indexName, type, id)
.source(jsonObject.toJSONString(), XContentType.JSON);
IndexResponse response = null;
try {
response = client.index(indexRequest);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("数据添加失败");
}
Map<String, Object> map = new HashMap<>();
map.put("id", response.getId());
map.put("version", response.getVersion());
map.put("index", response.getIndex());
map.put("type", response.getType());
return map;
}
@Override
public String deleteDoc(String indexName, String type, String id) {
DeleteRequest deleteRequest = new DeleteRequest(indexName, type, id);
DeleteResponse deleteResponse = null;
try {
deleteResponse = client.delete(deleteRequest);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("删除文档失败");
}
if (deleteResponse.status() == RestStatus.NOT_FOUND) {
return EsStatus.NOTFOUNE;
}
return EsStatus.SUCCESS;
}
@Override
public Map<String, Object> localUpdateDoc(String indexName, String type, String id, Object data) {
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(data);
UpdateRequest updateRequest = new UpdateRequest(indexName, type, id)
.doc(jsonObject.toJSONString(), XContentType.JSON);
UpdateResponse response = null;
try {
response = client.update(updateRequest);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("修改失败");
}
Map<String, Object> map = new HashMap<>();
map.put("id", response.getId());
map.put("version", response.getVersion());
map.put("index", response.getIndex());
map.put("type", response.getType());
return map;
}
@Override
public GetResponse findById(String indexName, String type, String id) {
GetRequest getRequest = new GetRequest(indexName, type, id);
GetResponse response = null;
try {
response = client.get(getRequest);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("查询失败");
}
return response;
}
@Override
public SearchHits findByIds(String indexName, String type, String[] ids) {
SearchRequest searchRequest = new SearchRequest(indexName);
if (StringUtils.isNotEmpty(ids)) {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds(ids);
sourceBuilder.query(queryBuilder);
sourceBuilder.size(ids.length);
sourceBuilder.sort(new FieldSortBuilder("_id"));
searchRequest.source(sourceBuilder);
}
searchRequest.types(type);
SearchResponse searchResponse = null;
try {
searchResponse = client.search(searchRequest);
} catch (IOException e) {
e.printStackTrace();
}
SearchHits searchHits = searchResponse.getHits();
return searchHits;
}
}