ElasticSearch-RestHighLevelClient常用查询总结

配置文件:

es:
  hosts: 10.10.10.10:9200,10.10.10.11:9200,10.10.10.12:9200
  username: elastic
  password: elastic
ext {
    elasticsearchVersion = '7.8.0'
}    

    implementation "org.elasticsearch.client:transport:$elasticsearchVersion"
    implementation "org.elasticsearch:elasticsearch:$elasticsearchVersion"
    implementation "org.elasticsearch.plugin:transport-netty4-client:$elasticsearchVersion"
    implementation "org.elasticsearch.client:elasticsearch-rest-high-level-client:$elasticsearchVersion"

配置类:

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
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.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;

import java.util.List;


@Configuration
public class ElasticsearchConfig {
    @Value("#{'${es.hosts}'.split(',')}")
    private List hosts;
    @Value("${es.username}")
    private String username;
    @Value("${es.password}")
    private String password;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HttpHost[] esHosts = hosts.stream().filter(StringUtils::isNotBlank).map(it -> {
            String[] split = it.split(":");
            return new HttpHost(split[0], Integer.parseInt(split[1]), "http");
        }).toArray(HttpHost[]::new);
        if(StrUtil.isNotBlank(username) && StrUtil.isNotBlank(password)){
			final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));

			RestClientBuilder builder = RestClient.builder(esHosts).setRequestConfigCallback(requestConfigBuilder -> {
				requestConfigBuilder.setConnectTimeout(-1);
				requestConfigBuilder.setSocketTimeout(-1);
				requestConfigBuilder.setConnectionRequestTimeout(-1);
				return requestConfigBuilder;
			}).setHttpClientConfigCallback(httpClientBuilder -> {
				httpClientBuilder.disableAuthCaching();
				return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
			});

			RestHighLevelClient client = new RestHighLevelClient(builder);
			return client;
		}else{
			RestClientBuilder builder = RestClient.builder(esHosts).setRequestConfigCallback(requestConfigBuilder -> {
				requestConfigBuilder.setConnectTimeout(180000);
				requestConfigBuilder.setSocketTimeout(180000);
				requestConfigBuilder.setConnectionRequestTimeout(180000);
				return requestConfigBuilder;
			});

			RestHighLevelClient client = new RestHighLevelClient(builder);
			return client;
		}
    }
}

match、match_phrase、query_string、wildcard、regexp、term、terms、nested、range等相关查询总结

ES相关查询Java版本:

import cn.hutool.core.collection.ListUtil;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

/**
 * @author meng
 */
public class BaseSearchSourceBuilder {

    public SearchSourceBuilder searchSourceBuilder() {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /**
         * match查询keyword字段,match会被分词,而keyword不会被分词,match需要跟keyword的完全匹配
         * match查询text字段,match分词,text也分词,只要match的分词结果和text的分词结果有相同的就匹配
         */
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", "ElasticSearch"));
        /**
         * match_phrase匹配keyword字段,需要完全匹配
         * match_phrase匹配text字段,match_phrase是分词的,text也是分词的,match_phrase的分词结果必须在text字段分词中都包含,而且顺序必须相同,而且必须都是连续的
         */
        boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("title", "ElasticSearch"));
        /**
         * query_string查询key类型的字段,无法查询
         * query_string查询text类型的字段,与match_phrase区别的是,不需要连续,顺序还可以调换
         * query_string基于运算符的查询字符串,例如 AND 或者 OR
         * 官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_boolean_operators
         */
        boolQueryBuilder.must(QueryBuilders.queryStringQuery("ElasticSearch").field("title"));
    //精准查询
    boolQueryBuilder.should(QueryBuilders.queryStringQuery(keyword).field(EsConstant.ES_FIELD_AUTHOR_NAME).type(MultiMatchQueryBuilder.Type.PHRASE).defaultOperator(Operator.AND));
        /**
         * wildcard通配符查询也是一种底层基于词的查询,与前缀查询不同的是它允许指定匹配的正则式。它使用标准的 shell 通配符查询: ? 匹配任意字符, * 匹配 0 或多个字符
         * 查询可能会消耗非常多的资源,使用需谨慎
         */
        boolQueryBuilder.must(QueryBuilders.wildcardQuery("title", "W?F*HW"));
        /**
         * regexp正则式查询
         * 查询可能会消耗非常多的资源,使用需谨慎
         */
        boolQueryBuilder.must(QueryBuilders.regexpQuery("title", "W[0-9].+"));
        /**
         * term查询keyword字段,term不会分词。而keyword字段也不分词,需要完全匹配
         * term查询text字段,因为text字段会分词,而term不分词,所以term查询的条件必须是text字段分词后的某一个
         */
        boolQueryBuilder.filter(QueryBuilders.termQuery("name", "ElasticSearch"));
        /**
         * list查询
         */
        boolQueryBuilder.filter(QueryBuilders.termsQuery("title.keyword", ListUtil.of("ElasticSearch")));
        /**
         * nested查询
         */
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termsQuery("users.id", "1"));
        boolQueryBuilder.must(QueryBuilders.nestedQuery("users", queryBuilder, ScoreMode.None));
        /**
         * 时间区间查询,使用时间戳
         */
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publish_time").gte("1648971574000").lte("1648971604665"));
        /**
         * 分页与排序
         */
        return new SearchSourceBuilder().query(boolQueryBuilder).from(0).size(10).sort("publish_time", SortOrder.DESC);
    }

}

你可能感兴趣的:(#,SpringBoot,#,ElasticSearch,elasticsearch,搜索引擎)