说明:这实例中的代码包含6.x和7.x版本,其中接口以6为后缀的为6.3.1版本,无6后缀的为7.2.0版本,spring boot版本为2.0.3。
ES官方文档已经说明7摒弃了type的概念,此文档对需要将ES版本由6升至7的场景有一定的借鉴意义。另外,6和7的代码皆验证通过,ES的JAVA客户端API目前比较流行RestHighLevelClient。
配置:
//compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-high-level-client', version: '7.2.0'
compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-high-level-client', version: '6.3.1'
// https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch
//compile group: 'org.elasticsearch', name: 'elasticsearch', version: '7.2.0'
//compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-client', version: '7.2.0'
compile group: 'org.elasticsearch', name: 'elasticsearch', version: '6.3.1'
Bean类:
public class ESUserInfoBean {
private Long userId;
private String userName;
private String lowerUserName;
private String showId;
private String headPic;
private Integer userType;
private String createTime;
private String updateTime;
private float score;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLowerUserName() {
return lowerUserName;
}
public void setLowerUserName(String lowerUserName) {
this.lowerUserName = lowerUserName;
}
public String getShowId() {
return showId;
}
public void setShowId(String showId) {
this.showId = showId;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
检索结果类:
public class ESUserInfoResult {
private List<ESUserInfoBean> datas;
private long totalHits;
public List<ESUserInfoBean> getDatas() {
return datas;
}
public void setDatas(List<ESUserInfoBean> datas) {
this.datas = datas;
}
public long getTotalHits() {
return totalHits;
}
public void setTotalHits(long totalHits) {
this.totalHits = totalHits;
}
}
驱动接口实现:
/**
* @author: wangkui
* @create: 2019/08/06$ 18:32$
* @desp:
**/
@Component
public class ESUserInfoDriverImpl implements ESUserInfoDriver {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private RestHighLevelClient restClient = null;
private String preTags = ""; //高亮前缀
private String postTags = ""; //高亮后缀
@Value("${community.elastic.host}")
private String hosts = ""; // 集群地址
@Value("${community.elastic.port}")
private String port = "9200"; // 使用的端口号
@Value("${community.elastic.schema}")
private String schema = "http"; // 使用的协议
@Value("${community.elastic.timeout}")
private String timeout = "10000"; //搜索超时时间
@Value("${community.elastic.connectTimeOut}")
private String connectTimeOut = "10000";
@Value("${community.elastic.socketTimeout}")
private String socketTimeout = "10000";
@Value("${community.elastic.connectionRequestTimeout}")
private String connectionRequestTimeout = "10000";
@Value("${community.elastic.maxConnTotal}")
private String maxConnTotal = "20";
@Value("${community.elastic.maxConnPerRoute}")
private String maxConnPerRoute = "20";
@Value("${community.elastic.userName}")
private String userName = "";
@Value("${community.elastic.password}")
private String password = "";
@Value("${community.elastic.numberOfShards}")
private Integer numberOfShards = 3;
@Value("${community.elastic.numberOfReplicas}")
private Integer numberOfReplicas = 1;
@Value("${community.elastic.requestTimeout}")
private Integer requestTimeout = 2;
@Value("${community.elastic.requestMasterTimeout}")
private Integer requestMasterTimeout = 2;
@PostConstruct
public void open()
{
try {
if (hosts == null || hosts.length() <= 0){
logger.info("ES集群地址不能为空!无法完成初始化.");
return ;
}
if (port == null || port.length() <= 0){
logger.info("ES端口后不能为空!无法完成初始化.");
return ;
}
if (schema == null || schema.length() <= 0){
logger.info("ES协议不能为空!无法完成初始化.");
return ;
}
ArrayList<HttpHost> hostList = new ArrayList<>();
String[] hostStrs = hosts.split(",");
for (String host : hostStrs) {
hostList.add(new HttpHost(host, Integer.parseInt(port), schema));
}
RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]))
.setFailureListener(new RestClient.FailureListener() { // 连接失败策略
}).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
if (connectTimeOut != null && connectTimeOut.length() > 0){
requestConfigBuilder.setConnectTimeout(Integer.parseInt(connectTimeOut));
}
if (socketTimeout != null && socketTimeout.length() > 0){
requestConfigBuilder.setSocketTimeout(Integer.parseInt(socketTimeout));
}
if (connectionRequestTimeout != null && connectionRequestTimeout.length() > 0){
requestConfigBuilder.setConnectionRequestTimeout(Integer.parseInt(connectionRequestTimeout));
}
return requestConfigBuilder;
}
})
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
if (maxConnTotal != null && maxConnTotal.length() > 0){
httpClientBuilder.setMaxConnTotal(Integer.parseInt(maxConnTotal));
}
if (maxConnPerRoute != null && maxConnPerRoute.length() > 0){
httpClientBuilder.setMaxConnTotal(Integer.parseInt(maxConnPerRoute));
}
if (userName == null || password == null){
return httpClientBuilder;
}else{
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
});
restClient = new RestHighLevelClient(builder);
}
catch (Exception e)
{
e.printStackTrace();
logger.error("open failed. reason: " + e.getMessage());
}
}
/*
@Override
public boolean existIndex(String index)
{
try {
GetIndexRequest getIndexRequest = new GetIndexRequest(index);
boolean ret = restClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
return ret;
}
catch (Exception e)
{
e.printStackTrace();
logger.error("existIndex failed. reason: " + e.getMessage());
return false;
}
}
*/
@Override
public boolean existIndex6(String index)
{
try {
GetIndexRequest request = new GetIndexRequest().indices(index);
boolean ret = restClient.indices().exists(request);
return ret;
}
catch (Exception e)
{
e.printStackTrace();
logger.error("existIndex6 failed. reason: " + e.getMessage());
return false;
}
}
/*
@Override
public void createIndex(String index, String contentType)
{
try {
//create index, set index name
CreateIndexRequest request = new CreateIndexRequest(index);
//set shard and replicas cnt
request.settings(Settings.builder()
.put("index.number_of_shards",numberOfShards)
.put("index.number_of_replicas",numberOfReplicas)
);
// request.source("{\n" +
// " \"settings\": {\n" +
// " \"index\": {\n" +
// " \"number_of_shards\": 3,\n" +
// " \"number_of_replicas\": 1\n" +
// " },\n" +
// " \"analysis\": {\n" +
// " \"analyzer\": {\n" +
// " \"my_lowercase_analyzer\": {\n" +
// " \"filter\": \"lowercase\",\n" +
// " \"type\": \"custom\",\n" +
// " \"tokenizer\": \"keyword\"\n" +
// " }\n" +
// " }\n" +
// " }\n" +
// " },\n" +
// " \"mappings\": {\n" +
// " \"properties\": {\n" +
// " \"showId\": {\n" +
// " \"type\": \"keyword\",\n" +
// " \"index\": true\n" +
// " },\n" +
// " \"userName\": {\n" +
// " \"type\": \"keyword\",\n" +
// " \"index\": true,\n" +
// " \"analyzer\": \"my_lowercase_analyzer\",\n" +
// " \"search_analyzer\": \"my_lowercase_analyzer\"\n" +
// " },\n" +
// " \"createTime\": {\n" +
// " \"type\": \"date\",\n" +
// " \"index\": true,\n" +
// " \"format\": \"yyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis\"\n" +
// " }\n" +
// " }\n" +
// " }\n" +
// "}", XContentType.JSON);
//request.alias(new Alias("test"));
request.setTimeout(TimeValue.timeValueMinutes(requestTimeout));
request.setMasterTimeout(TimeValue.timeValueMinutes(requestMasterTimeout));
//request.waitForActiveShards(ActiveShardCount.from(2));
request.waitForActiveShards(ActiveShardCount.DEFAULT);
CreateIndexResponse response = restClient.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = response.isShardsAcknowledged();
boolean shardsAcknowledged = response.isShardsAcknowledged();
System.out.println("acknowledged = " + acknowledged);
System.out.println("shardsAcknowledged = " + shardsAcknowledged);
//client.close();
return;
}
catch (Exception e)
{
e.printStackTrace();
logger.error("createIndex error. reason: " + e.getMessage());
}
}
*/
@Override
public void createIndex6(String index, String contentType)
{
try
{
//create index, set index name
CreateIndexRequest request = new CreateIndexRequest(index);
//set shard and replicas cnt
request.settings(Settings.builder()
.put("index.number_of_shards",numberOfShards)
.put("index.number_of_replicas",numberOfReplicas)
);
//set index mapping
request.source(contentType, XContentType.JSON);
//request.alias(new Alias("test"));
//request.setTimeout(TimeValue.timeValueMinutes(requestTimeout));
//request.setMasterTimeout(TimeValue.timeValueMinutes(requestMasterTimeout));
request.waitForActiveShards(ActiveShardCount.DEFAULT);
CreateIndexResponse response = restClient.indices().create(request);
boolean acknowledged = response.isShardsAcknowledged();
boolean shardsAcknowledged = response.isShardsAcknowledged();
System.out.println("acknowledged = " + acknowledged);
System.out.println("shardsAcknowledged = " + shardsAcknowledged);
//client.close();
}
catch (Exception e)
{
e.printStackTrace();
logger.error("createIndex6 error. reason: " + e.getMessage());
}
}
/*
@Override
public boolean saveUserInfo(String index, ESUserInfoBean bean) {
if (restClient == null){
logger.info("系统未配置搜索服务参数,无法完成索引保存操作!");
return false;
}
if(bean == null){
logger.info("bean 对象为空,无法创建索引!");
return false;
}
if (index == null || index.length() <= 0){
logger.info("对象index为空,无法创建索引!");
return false;
}
XContentBuilder builder = getUserInfoXContentBuilder(bean);
UpdateRequest request = new UpdateRequest(index,
bean.getShowId())
.doc(builder)
.upsert(builder);//upsert--id不存在时就插入
try {
UpdateResponse response = restClient.update(request, RequestOptions.DEFAULT);
response.forcedRefresh();
if (response.status().equals(RestStatus.OK)
|| response.status().equals(RestStatus.CREATED)){
logger.info("索引文档[id = " + bean.getShowId() + ", index = " + index + "]保存成功!");
return true;
}else{
logger.info("保存失败,状态="+response.status()+" "+response.toString());
return false;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("saveUserInfo failed. reason: " + e.getMessage());
return false;
}
}
*/
@Override
public boolean saveUserInfo6(String index, ESUserInfoBean bean)
{
try {
if (restClient == null){
logger.info("系统未配置搜索服务参数,无法完成索引保存操作!");
return false;
}
if(bean == null){
logger.info("bean 对象为空,无法创建索引!");
return false;
}
if (index == null || index.length() <= 0){
logger.info("对象index为空,无法创建索引!");
return false;
}
XContentBuilder builder = getUserInfoXContentBuilder(bean);
UpdateRequest request = new UpdateRequest(index, "userinfo",
bean.getShowId())
.doc(builder)
.upsert(builder);//upsert--id不存在时就插入
UpdateResponse response = restClient.update(request);
response.forcedRefresh();
if (response.status().equals(RestStatus.OK)
|| response.status().equals(RestStatus.CREATED)){
logger.info("索引文档[id = " + bean.getShowId() + ", index = " + index + "]保存成功!");
return true;
}else{
logger.info("保存失败,状态="+response.status()+" "+response.toString());
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
logger.error("saveUserInfo6 failed. reason: " + e.getMessage());
return false;
}
}
/*
@Override
public boolean delete(String index, String id)
{
if (restClient == null){
logger.info("系统未配置搜索服务参数,无法完成索引删除操作!");
return false;
}
if (index == null || index.length() <= 0){
logger.info("index,定位索引!");
return false;
}
DeleteRequest request = new DeleteRequest()
.index(index)
.id(id);
try {
DeleteResponse deleteResponse = restClient.delete(
request, RequestOptions.DEFAULT);
if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
logger.info("未找到要删除的文档[" + id + "]");
return true;
}
if (deleteResponse.status().equals(RestStatus.OK)){
logger.info("文档[" + id + "]删除成功!");
return true;
}else{
logger.info("删除状态="+deleteResponse.status() + " "+deleteResponse.toString());
return false;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("delete failed. reason: " + e.getMessage());
return false;
}
}
*/
@Override
public boolean delete6(String index, String id)
{
if (restClient == null){
logger.info("系统未配置搜索服务参数,无法完成索引删除操作!");
return false;
}
if (index == null || index.length() <= 0){
logger.info("index,定位索引!");
return false;
}
DeleteRequest request = new DeleteRequest()
.index(index)
.type("userinfo")
.id(id);
try {
DeleteResponse deleteResponse = restClient.delete(
request);
if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
logger.info("未找到要删除的文档[" + id + "]");
return true;
}
if (deleteResponse.status().equals(RestStatus.OK)){
logger.info("文档[" + id + "]删除成功!");
return true;
}else{
logger.info("删除状态="+deleteResponse.status() + " "+deleteResponse.toString());
return false;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("delete6 failed. reason: " + e.getMessage());
return false;
}
}
/*
@Override
public ESUserInfoResult search(String index, SearchSourceBuilder sourceBuilder, int from, int size, String[] highlightFields) {
if (restClient == null){
logger.info("系统未配置搜索服务参数,无法完成检索操作!");
return null;
}
if (index == null || index.length() <= 0){
logger.info("index为空,无法定位索引!");
return null;
}
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
sourceBuilder.from(from); //设置from选项,确定要开始搜索的结果索引。 默认为0。
sourceBuilder.size(size); //设置大小选项,确定要返回的搜索匹配数。 默认为10。
if (timeout != null && timeout.length() > 0){
sourceBuilder.timeout(new TimeValue(Integer.parseInt(timeout)));
}
if (highlightFields != null){
HighlightBuilder highlightBuilder = new HighlightBuilder();
for (String highlightField : highlightFields){
HighlightBuilder.Field field = new HighlightBuilder.Field(highlightField);
highlightBuilder.field(field);
}
if (preTags != null && preTags.length() > 0
&& postTags != null && postTags.length() > 0){
highlightBuilder.preTags(preTags);
highlightBuilder.postTags(postTags);
}
sourceBuilder.highlighter(highlightBuilder);
}
searchRequest.source(sourceBuilder);
try {
SearchResponse response = restClient.search(searchRequest, RequestOptions.DEFAULT);
logger.info("文档搜索结果 status=" + response.status());
ESUserInfoResult esResult = new ESUserInfoResult();
SearchHits searchHits = response.getHits();
esResult.setTotalHits(searchHits.getTotalHits().value);
List<ESUserInfoBean> datas = new ArrayList<>();
Iterator<SearchHit> iterator = searchHits.iterator();
while (iterator.hasNext()){
SearchHit searchHit = iterator.next();
ESUserInfoBean data = JSON.parseObject(searchHit.getSourceAsString(), ESUserInfoBean.class);
data.setScore(searchHit.getScore());
if (highlightFields != null){
Map<String, HighlightField> hlFieldsMap = searchHit.getHighlightFields();
for (String highlightField : highlightFields){
if (hlFieldsMap.containsKey(highlightField)){
HighlightField highlight = hlFieldsMap.get(highlightField);
Text[] fragments = highlight.fragments();
if (fragments.length > 0){
StringBuffer sb = new StringBuffer();;
for (Text fragment : fragments){
sb.append(fragment.string());
}
if (highlightField.toLowerCase().equals("showId")){
data.setShowId(sb.toString());
} else if (highlightField.toLowerCase().equals("userName")){
data.setUserName(sb.toString());
} else {
logger.info("highlightField["+highlightField+"]不在ESUserInfoBean属性范围!");
}
}
}
}
}
datas.add(data);
}
esResult.setDatas(datas);
return esResult;
} catch (Exception e) {
e.printStackTrace();
logger.error("search failed. reason: " + e.getMessage());
return null;
}
}
*/
@Override
public ESUserInfoResult search6(String index, SearchSourceBuilder sourceBuilder, int from,
int size, String[] highlightFields)
{
if (restClient == null){
logger.info("系统未配置搜索服务参数,无法完成检索操作!");
return null;
}
if (index == null || index.length() <= 0){
logger.info("index为空,无法定位索引!");
return null;
}
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
searchRequest.types("userinfo");
sourceBuilder.from(from); //设置from选项,确定要开始搜索的结果索引。 默认为0。
sourceBuilder.size(size); //设置大小选项,确定要返回的搜索匹配数。 默认为10。
if (timeout != null && timeout.length() > 0){
sourceBuilder.timeout(new TimeValue(Integer.parseInt(timeout)));
}
if (highlightFields != null){
HighlightBuilder highlightBuilder = new HighlightBuilder();
for (String highlightField : highlightFields){
HighlightBuilder.Field field = new HighlightBuilder.Field(highlightField);
highlightBuilder.field(field);
}
if (preTags != null && preTags.length() > 0
&& postTags != null && postTags.length() > 0){
highlightBuilder.preTags(preTags);
highlightBuilder.postTags(postTags);
}
sourceBuilder.highlighter(highlightBuilder);
}
searchRequest.source(sourceBuilder);
try {
SearchResponse response = restClient.search(searchRequest);
logger.info("文档搜索结果 status=" + response.status());
ESUserInfoResult esResult = new ESUserInfoResult();
SearchHits searchHits = response.getHits();
esResult.setTotalHits(searchHits.getTotalHits());
List<ESUserInfoBean> datas = new ArrayList<>();
Iterator<SearchHit> iterator = searchHits.iterator();
while (iterator.hasNext()){
SearchHit searchHit = iterator.next();
ESUserInfoBean data = JSON.parseObject(searchHit.getSourceAsString(), ESUserInfoBean.class);
data.setScore(searchHit.getScore());
if (highlightFields != null){
Map<String, HighlightField> hlFieldsMap = searchHit.getHighlightFields();
for (String highlightField : highlightFields){
if (hlFieldsMap.containsKey(highlightField)){
HighlightField highlight = hlFieldsMap.get(highlightField);
Text[] fragments = highlight.fragments();
if (fragments.length > 0){
StringBuffer sb = new StringBuffer();;
for (Text fragment : fragments){
sb.append(fragment.string());
}
if (highlightField.toLowerCase().equals("showId")){
data.setShowId(sb.toString());
} else if (highlightField.toLowerCase().equals("userName")){
data.setUserName(sb.toString());
} else {
logger.info("highlightField["+highlightField+"]不在ESUserInfoBean属性范围!");
}
}
}
}
}
datas.add(data);
}
esResult.setDatas(datas);
return esResult;
} catch (Exception e) {
e.printStackTrace();
logger.error("search6 failed. reason: " + e.getMessage());
return null;
}
}
/*
@PreDestroy
@Override
public void close() {
try {
if (restClient != null){
restClient.close();
restClient = null;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("close failed. reason: " + e.getMessage());
}
}
*/
@PreDestroy
@Override
public void close6()
{
try {
if (restClient != null){
restClient.close();
restClient = null;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("close failed6. reason: " + e.getMessage());
}
}
private XContentBuilder getUserInfoXContentBuilder(ESUserInfoBean bean)
{
XContentBuilder builder = null;
try {
builder = XContentFactory.jsonBuilder().startObject()
.field("userId", bean.getUserId())
.field("userName", bean.getUserName())
.field("lowerUserName", bean.getLowerUserName())
.field("showId", bean.getShowId())
.field("headPic", bean.getHeadPic())
.field("userType", bean.getUserType())
.field("createTime", bean.getCreateTime())
.field("updateTime", bean.getUpdateTime())
.endObject();
} catch (Exception e) {
e.printStackTrace();
logger.error("getUserInfoXContentBuilder failed. reason: " + e.getMessage());
}
return builder;
}
}
创建索引伪代码:
if (!esDriver.existIndex6(AccountFmtType.ES_INDEX))
{
/* ES7
String contentType = "{\n" +
" \"properties\": {\n" +
" \"showId\": {\n" +
" \"type\": \"keyword\",\n" +
" \"index\": true,\n" +
"\t \"filter\": \"lowercase\"\n" +
" },\n" +
"\t\"lowerUserName\": {\n" +
" \"type\": \"keyword\",\n" +
" \"index\": true,\n" +
"\t \"filter\": \"lowercase\"\n" +
" },\n" +
"\t\"createTime\": {\n" +
" \"type\": \"date\",\n" +
" \"index\": true,\n" +
"\t \"format\": \"yyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis\"\n" +
" }\n" +
" }\n" +
"}";
*/
String contentType = "{\n" +
" \"mappings\": \n" +
" {\n" +
"\t\"userinfo\":\n" +
"\t{\n" +
"\t\t\"properties\": {\n" +
"\t\t\"showId\": {\n" +
"\t\t \"type\": \"keyword\",\n" +
"\t\t \"index\": true\n" +
"\t\t},\n" +
"\t\t\"lowerUserName\": {\n" +
"\t\t \"type\": \"keyword\",\n" +
"\t\t \"index\": true\n" +
"\t\t},\n" +
"\t\t\"createTime\": {\n" +
"\t\t \"type\": \"date\",\n" +
"\t\t \"index\": true,\n" +
"\t\t \"format\": \"yyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis\"\n" +
"\t\t}\n" +
"\t }\n" +
"\t}\n" +
" }\n" +
"}";
esDriver.createIndex6(AccountFmtType.ES_INDEX, contentType);
检索伪代码:
String tmpContent = request.getContent().toLowerCase().replace("*", "\\*").replace("?", "\\?");
String likeContent = "*" + tmpContent + "*";
String content = request.getContent().toLowerCase();
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
String beginTime = "1970/01/01 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String endTime = sdf.format(new Date(request.getReqTime() > 0 ? request.getReqTime() : System.currentTimeMillis()));
/* ES7
sourceBuilder.query(
QueryBuilders.boolQuery().must(
QueryBuilders.boolQuery()
.should(QueryBuilders.wildcardQuery("lowerUserName.keyword", likeContent).boost((float) 0.5))
.should(QueryBuilders.wildcardQuery("showId.keyword", likeContent).boost((float) 0.2))
.should(QueryBuilders.matchQuery("lowerUserName.keyword", content).boost((float) 2.0))
.should(QueryBuilders.matchQuery("showId.keyword", content).boost((float) 5.0))
)
.filter(QueryBuilders.rangeQuery("createTime").from(beginTime).to(endTime))
);
*/
sourceBuilder.query(
QueryBuilders.boolQuery().must(
QueryBuilders.boolQuery()
.should(QueryBuilders.wildcardQuery("lowerUserName", likeContent).boost((float) 0.5))
.should(QueryBuilders.wildcardQuery("showId", likeContent).boost((float) 0.2))
.should(QueryBuilders.matchQuery("lowerUserName", content).boost((float) 2.0))
.should(QueryBuilders.matchQuery("showId", content).boost((float) 5.0))
)
.filter(QueryBuilders.rangeQuery("createTime").from(beginTime).to(endTime))
);
int size = request.getPageSize().intValue();
int from = request.getPage().intValue() * size;
ESUserInfoResult result = esDriver.search6(AccountFmtType.ES_INDEX, sourceBuilder, from, size, null);