非maven引入方式jar包下载地址
链接: https://pan.baidu.com/s/1G2K6MkmRqf1aSELb8hZzOg 提取码: gfnb 复制这段内容后打开百度网盘手机App,操作更方便哦
maven引入参考官方文档即可,代码仅供参考,业务逻辑还是得自己实现,对性能要求高的查询可考虑scroll。
package com.treasurebox.framework.es;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
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.client.HttpAsyncResponseConsumerFactory;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import com.alibaba.fastjson.JSONObject;
import com.treasurebox.entity.Boon;
import com.treasurebox.framework.page.Page;
import com.treasurebox.util.JsonUtils;
public class ElasticsearchUtil {
private static final Log LOG = LogFactory.getLog(ElasticsearchUtil.class);
private static String elasticHostName = "ES实例host";
private static String elasticUserName = "账号";
private static String elasticPassword = "密码";
private static String boonIndex = "boon";
private static RestHighLevelClient restHighLevelClient;
private static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// 默认缓存限制为100MB,此处修改为30MB。
builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(
30 * 1024 * 1024));
COMMON_OPTIONS = builder.build();
}
static RestHighLevelClient getRestHighLevelClient() {
if (restHighLevelClient == null) {
// 阿里云ES集群需要basic auth验证。
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// 访问用户名和密码为您创建阿里云Elasticsearch实例时设置的用户名和密码,也是Kibana控制台的登录用户名和密码。
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(elasticUserName,
elasticPassword));
// 通过builder创建rest client,配置http client的HttpClientConfigCallback。
// 单击所创建的Elasticsearch实例ID,在基本信息页面获取公网地址,即为ES集群地址。
RestClientBuilder restClientBuilder = RestClient.builder(
new HttpHost(elasticHostName, 9200))
.setHttpClientConfigCallback(
new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
// RestHighLevelClient实例通过REST low-level client builder进行构造。
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
return restHighLevelClient;
} else {
return restHighLevelClient;
}
}
/**
* 添加搜索的商品
*/
public static void addBoonList(List<Boon> boonsList) {
RestHighLevelClient restHighLevelClient = getRestHighLevelClient();
boonsList.forEach(boon -> {
// boon.setDetail(
// boon.getName() + boon.getAddress() + boon.getDetail());
try {
IndexRequest indexRequest = new IndexRequest(boonIndex);
indexRequest.id(boon.getId().toString());
indexRequest.source(JsonUtils.toJSONString(boon),
XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(
indexRequest, COMMON_OPTIONS);
LOG.info(indexResponse);
} catch (Exception e) {
LOG.error(e, e);
}
});
}
public static void updateBoon(Boon boon) {
if (boon.getStatus() == 1) {
addBoon(boon);
} else {
deleteBoon(boon);
}
}
/**
* 添加商品
*/
public static void addBoon(Boon boon) {
RestHighLevelClient restHighLevelClient = getRestHighLevelClient();
try {
IndexRequest indexRequest = new IndexRequest(boonIndex);
indexRequest.id(boon.getId().toString());
indexRequest
.source(JsonUtils.toJSONString(boon), XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(
indexRequest, COMMON_OPTIONS);
LOG.info(indexResponse);
} catch (Exception e) {
LOG.error(e, e);
}
}
/**
* 删除商品
*/
public static void deleteBoon(Boon boon) {
RestHighLevelClient restHighLevelClient = getRestHighLevelClient();
try {
DeleteRequest deleteRequest = new DeleteRequest(boonIndex, boon
.getId().toString());
DeleteResponse deleteResponse = restHighLevelClient.delete(
deleteRequest, COMMON_OPTIONS);
LOG.info(deleteResponse);
} catch (Exception e) {
LOG.error(e, e);
}
}
/**
* 获取搜索的商品
*/
public static Page searchBoonList(Page p, String keyword) {
LOG.info("开始全文检索");
LOG.info("当前页面" + p.getPageNo());
LOG.info("分页数量" + p.getPageSize());
RestHighLevelClient restHighLevelClient = getRestHighLevelClient();
try {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, "name",
"address", "detail"));
sourceBuilder.from((p.getPageNo() - 1) * 10);
sourceBuilder.size(p.getPageSize());
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(boonIndex);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(
searchRequest, RequestOptions.DEFAULT);
// LOG.info(searchResponse);
List<Boon> boonList = new ArrayList<>();
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (int i = 0; i < searchHits.length; i++) {
Boon boon = JSONObject.toJavaObject(JSONObject
.parseObject(searchHits[i].getSourceAsString()),
Boon.class);
boonList.add(boon);
}
p.setRows(boonList);
LOG.info(searchResponse.getHits().getTotalHits().value);
p.setTotal((int) searchResponse.getHits().getTotalHits().value);
return p;
} catch (Exception e) {
LOG.error(e, e);
}
return p;
}
}