精华内容
下载资源
问答
  • ES 查询语句
    2022-04-12 17:59:31

    1.match,匹配包含 “rock” “climbing”,二者可以分开出现

    全文搜索 | Elasticsearch: 权威指南 | Elastic

    GET /megacorp/employee/_search
    {
        "query" : {
            "match" : {
                "about" : "rock climbing"
            }
        }
    }

    2.match_phrase,仅匹配同时包含 “rock” “climbing” ,并且 二者以短语 “rock climbing” 的形式紧挨着的雇员记录。

    短语搜索 | Elasticsearch: 权威指南 | Elastic

    GET /megacorp/employee/_search
    {
        "query" : {
            "match_phrase" : {
                "about" : "rock climbing"
            }
        }
    }

    更多相关内容
  • ElasticSearch查询语句

    2020-10-10 15:20:53
    ElasticSearch查询学习;ElasticSearch查询学习;ElasticSearch查询学习;ElasticSearch查询学习;ElasticSearch查询学习;ElasticSearch查询学习;
  • elasticsearch通用查询语句生成

    千次阅读 2021-09-30 15:03:57
    elasticsearch通用搜索语句生成工具,上层搜索语句同阿里云opensearch搜索语句相同,方便搜索引擎透明迁移。

    目录

    1.目的

    2.maven依赖

    3.通用查询语句生成代码


    1.目的

        使用一种通用查询语句,方便其他服务调用es搜索,通用查询参数同阿里云的开放搜索openSearch参数一致(1.公司搜索原来使用的就是阿里云的开放搜索,其它业务不用怎么修改就替换了 2.阿里云的开放搜索语句和参数设计的比较完善,毕竟对方是专业并收费的)

    {
    	"dataAmount": "10",
    	"andFilter": "min_amount<=50,display_start_date<=1632728060134,(display_end_date='' OR display_end_date>=1632728060134),",
    	"searchParam": "(platform_type:'1' OR platform_type:'3') AND default:'5473' AND is_active:'2' AND item_type:'2' AND (item_state:'6' OR item_state:'7')",
    	"dataStart": "0",
    	"sort": "pay_amount:DECREASE;shelves_date:DECREASE"
    }

    参数说明:

    dataStart:起始行
    dataAmount:页大小
    searchParam:模糊搜索参数
    andFilter:过滤参数
    sort:排序参数
    

     2.maven依赖

            <!-- elasticsearch start -->
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-client</artifactId>
                <version>7.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
          <!-- elasticsearch end -->

    3.通用查询语句生成代码

    package com.ybjdw.messageserve.utils;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.ybjdw.base.utils.DateUtils;
    import org.apache.commons.lang.StringUtils;
    import org.elasticsearch.index.query.BoolQueryBuilder;
    import org.elasticsearch.index.query.MatchQueryBuilder;
    import org.elasticsearch.index.query.QueryBuilder;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.elasticsearch.search.builder.SearchSourceBuilder;
    import org.elasticsearch.search.sort.FieldSortBuilder;
    import org.elasticsearch.search.sort.SortOrder;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.List;
    
    /**
     * author: zhanggw
     * 创建时间:  2021/9/27
     */
    public class SearchUtil {
        private final static Logger logger = LoggerFactory.getLogger(SearchUtil.class);
    
        public final static String OPERATOR_GTE = ">=";
        public final static String OPERATOR_LTE = "<=";
        public final static String OPERATOR_NET = "!=";
        public final static String OPERATOR_GT = ">";
        public final static String OPERATOR_ET = "=";
        public final static String OPERATOR_LT = "<";
        public final static String OPERATOR_AND = "AND";
        public final static String OPERATOR_OR = "OR";
        private final static List<String> OPERATOR_LIST = new ArrayList<>(Arrays.asList(OPERATOR_GTE,OPERATOR_LTE,OPERATOR_NET,OPERATOR_GT,OPERATOR_ET,OPERATOR_LT));
        public final static List<String> FIELD_DATE_LIST = new ArrayList<>(Arrays.asList("displayStartDate","displayEndDate","createDate","modifyDate",OPERATOR_ET,OPERATOR_LT));
    
        /**
         * <一句话功能简述> 生成通用es查询
         * <功能详细描述>
         *{
         * 	"dataAmount": "10",
         * 	"andFilter": "display_start_date<=1632624039672,(display_end_date=0 OR display_end_date>=1632624039672),",
         * 	"searchParam": "default:'6018' AND is_active:'2' AND item_type:'2' AND item_state:'6'",
         * 	"dataStart": "0",
         * 	"sort": "pay_amount:DECREASE;shelves_date:DECREASE"
         * }
         * author: zhanggw
         * 创建时间:  2021/9/27
         */
        public static SearchSourceBuilder generateEsQuery(JSONObject searchTermJson){
            try{
                if(searchTermJson == null){
                    return null;
                }
    
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    
                // 总查询条件
                BoolQueryBuilder topQuery = QueryBuilders.boolQuery();
    
                // 模糊搜索添加参数
                matchAddSearchParam(topQuery, searchTermJson.getString("searchParam"));
    
                // 精确搜索添加参数
                termAddSearchParam(topQuery, searchTermJson.getString("termParam"));
    
                // 添加过滤器
                String filterParamStr = searchTermJson.getString("andFilter");
                queryAddFilter(topQuery, filterParamStr);
    
                sourceBuilder.query(topQuery);
    
                // 添加分页
                Integer dataStartInteger = searchTermJson.getInteger("dataStart");
                Integer dataAmountInteger = searchTermJson.getInteger("dataAmount");
                if(dataStartInteger != null){
                    sourceBuilder.from(dataStartInteger);
                }
                if(dataAmountInteger != null){
                    sourceBuilder.size(dataAmountInteger);
                }
    
                // 添加展示字段
                String showFieldStr = searchTermJson.getString("showFields");
                String excludeFieldStr = searchTermJson.getString("excludeFields");
                searchAddShowField(sourceBuilder, showFieldStr, excludeFieldStr);
    
                // 添加排序
                queryAddSort(sourceBuilder, searchTermJson.getString("sort"));
                return sourceBuilder;
            }catch (Exception e){
                logger.error("生成通用es查询异常!", e);
            }
            return null;
        }
    
        /**
         * <一句话功能简述> 在BoolQueryBuilder上添加展示字段
         * <功能详细描述>
         * author: zhanggw
         * 创建时间:  2021/11/5
         */
        private static void searchAddShowField(SearchSourceBuilder sourceBuilder, String showFieldStr, String excludeFieldStr) {
            try{
                String[] showFieldArray = null;
                if(showFieldStr != null){
                    showFieldArray = showFieldStr.split(",");
                    showFieldArray = camelCaseNameArray(showFieldArray);
                }
    
                String[] excludeFieldArray = null;
                if(excludeFieldStr != null){
                    excludeFieldArray = excludeFieldStr.split(",");
                    excludeFieldArray = camelCaseNameArray(excludeFieldArray);
                }
    
                sourceBuilder.fetchSource(showFieldArray, excludeFieldArray);
            }catch (Exception e){
                logger.error("查询添加展示字段异常!", e);
            }
        }
    
        private static String[] camelCaseNameArray(String[] showFieldArray) {
            try{
                if(showFieldArray == null || showFieldArray.length == 0){
                    return showFieldArray;
                }
    
                String[] newFieldArray = new String[showFieldArray.length];
                for(int i=0; i < showFieldArray.length; i++){
                    newFieldArray[i] = camelCaseName(showFieldArray[i]);
                }
                return newFieldArray;
            }catch (Exception e){
                logger.error("转换字符串数组驼峰异常!", e);
                return showFieldArray;
            }
        }
    
        /**
         * <一句话功能简述> 在BoolQueryBuilder中添加模糊匹配
         * <功能详细描述>
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param searchParamStr 模糊搜索参数  (platform_type:'1' OR platform_type:'3') AND default:'5473' AND is_active:'2' AND item_type:'2' AND (item_state:'6' OR item_state:'7')
         */
        private static void matchAddSearchParam(BoolQueryBuilder topQuery, String searchParamStr) {
            try{
                if(topQuery == null || StringUtils.isBlank(searchParamStr)){
                    return;
                }
    
                logger.trace("BoolQueryBuilder开始添加模糊搜索参数,searchParam:{}", searchParamStr);
                String[] searchParamArray = searchParamStr.split(OPERATOR_AND);
                if(searchParamArray.length > 0){
                    for(String searchParam:searchParamArray){ // 第一层and filter
                        searchParam = searchParam.trim();
                        if(StringUtils.isBlank(searchParam)){
                            continue;
                        }
    
                        if(searchParam.contains("OR")){ // 搜索带or
                            searchParam = searchParam.replace("(","").replace(")","");
                            String[] orMatchArray = searchParam.split(OPERATOR_OR);
                            if(orMatchArray.length > 0){
                                logger.trace("or match,searchParam:{}", searchParam);
                                BoolQueryBuilder orMatchQuery = QueryBuilders.boolQuery();
                                for(String orSubMatch:orMatchArray){
                                    QueryBuilder matchQuery = getMatchQuery(orSubMatch);
                                    if(matchQuery != null){
                                        orMatchQuery.should(matchQuery);
                                    }
                                }
                                topQuery.must(orMatchQuery);
                            }
                        }else{
                            QueryBuilder matchQuery = getMatchQuery(searchParam);
                            if(matchQuery != null){
                                topQuery.must(matchQuery);
                            }
                        }
                    }
                }
            }catch (Exception e){
                logger.error("topQuery添加过滤条件异常!", e);
            }
        }
    
        /**
         * <一句话功能简述> 在BoolQueryBuilder中添加精确匹配
         * <功能详细描述>
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param termParamStr 精确搜索参数  (platform_type:'1' OR platform_type:'3') AND default:'5473' AND is_active:'2' AND item_type:'2' AND (item_state:'6' OR item_state:'7')
         */
        private static void termAddSearchParam(BoolQueryBuilder topQuery, String termParamStr) {
            try{
                if(topQuery == null || StringUtils.isBlank(termParamStr)){
                    return;
                }
    
                logger.trace("BoolQueryBuilder开始添加精确搜索参数,termParamStr:{}", termParamStr);
                String[] termParamArray = termParamStr.split(OPERATOR_AND);
                if(termParamArray.length > 0){
                    for(String termParam:termParamArray){ // 第一层and filter
                        termParam = termParam.trim();
                        if(StringUtils.isBlank(termParam)){
                            continue;
                        }
    
                        if(termParam.contains("OR")){ // 搜索带or
                            termParam = termParam.replace("(","").replace(")","");
                            String[] orTermArray = termParam.split(OPERATOR_OR);
                            if(orTermArray.length > 0){
                                logger.trace("or term,termParam:{}", termParam);
                                BoolQueryBuilder orTermQuery = QueryBuilders.boolQuery();
                                for(String orSubTerm:orTermArray){
                                    QueryBuilder termQuery = getTermQuery(orSubTerm);
                                    if(termQuery != null){
                                        orTermQuery.should(termQuery);
                                    }
                                }
                                topQuery.must(orTermQuery);
                            }
                        }else{
                            QueryBuilder termQuery = getTermQuery(termParam);
                            if(termQuery != null){
                                topQuery.must(termQuery);
                            }
                        }
                    }
                }
            }catch (Exception e){
                logger.error("topQuery添加过滤条件异常!", e);
            }
        }
    
        /**
         * <一句话功能简述> 在BoolQueryBuilder中添加过滤条件
         * <功能详细描述> 
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param andFilterStr "display_start_date<=1632624039672,(display_end_date='' OR display_end_date>=1632624039672),",
         */
        private static void queryAddFilter(BoolQueryBuilder topQuery, String andFilterStr) {
            try{
                if(topQuery == null || StringUtils.isBlank(andFilterStr)){
                    return;
                }
    
                logger.trace("BoolQueryBuilder开始添加过滤条件,andFilterStr:{}", andFilterStr);
                String[] filterConditionArray = andFilterStr.split(",");
                if(filterConditionArray.length > 0){
                    for(String filterCondition:filterConditionArray){ // 第一层and filter
                        filterCondition = filterCondition.trim();
                        if(StringUtils.isBlank(filterCondition)){
                            continue;
                        }
                        filterCondition = filterCondition.replace("or", OPERATOR_OR);
    
                        if(filterCondition.contains(OPERATOR_OR)){ // 过滤中带or
                            filterCondition = filterCondition.replace("(","").replace(")","");
                            String[] orFilterArray = filterCondition.split(OPERATOR_OR);
                            if(orFilterArray.length > 0){
                                BoolQueryBuilder orFilterQuery = QueryBuilders.boolQuery();
                                for(String orSubFilter:orFilterArray){
                                    orFilterQuery.should(getFilterQuery(orSubFilter));
                                }
                                topQuery.filter(orFilterQuery);
                            }
                        }else{
                            topQuery.filter(getFilterQuery(filterCondition));
                        }
                    }
                }
            }catch (Exception e){
                logger.error("topQuery添加过滤条件异常!", e);
            }
        }
    
        /**
         * <一句话功能简述> 过滤基本语句转化
         * <功能详细描述>
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param filterParamBasic 过滤基本语句 display_start_date<=1632624039672
         */
        private static QueryBuilder getFilterQuery(String filterParamBasic) {
            QueryBuilder queryBuilder = null;
            for(String operator:OPERATOR_LIST){
                if(filterParamBasic.contains(operator)){
                    String[] filterArray = filterParamBasic.split(operator);
                    String filterName = camelCaseName(filterArray[0]);
                    filterName = filterName.trim();
                    String filterValue = filterArray[1];
                    filterValue = processFilterParam(filterName, filterValue); // 处理过滤参数,业务相关
                    logger.trace("filterParamBasic:{},filterName:{},filterValue:{}", filterParamBasic,filterName, filterValue);
                    switch (operator){
                        case SearchUtil.OPERATOR_GTE:
                            queryBuilder = QueryBuilders.rangeQuery(filterName).gte(filterValue);
                            break;
                        case SearchUtil.OPERATOR_NET:
                            if(StringUtils.isBlank(filterValue)){
                                queryBuilder = QueryBuilders.existsQuery(filterName);
                            }else{
                                queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery(filterName, filterValue));
                            }
                            break;
                        case SearchUtil.OPERATOR_LTE:
                            queryBuilder = QueryBuilders.rangeQuery(filterName).lte(filterValue);
                            break;
                        case SearchUtil.OPERATOR_GT:
                            queryBuilder = QueryBuilders.rangeQuery(filterName).gt(filterValue);
                            break;
                        case SearchUtil.OPERATOR_ET:
                            if(StringUtils.isBlank(filterValue)){
                                queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(filterName));
                            }else{
                                queryBuilder = QueryBuilders.termQuery(filterName, filterValue);
                            }
                            break;
                        case SearchUtil.OPERATOR_LT:
                            queryBuilder = QueryBuilders.rangeQuery(filterName).lt(filterValue);
                            break;
                    }
                    break;
                }
            }
    
            return queryBuilder;
        }
    
        private static String preProcessFilter(String filterParamStr) {
            try{
                filterParamStr = filterParamStr.replace("display_end_date=0", "display_end_date=''");
            }catch (Exception e){
                logger.error("es过滤参数预处理异常!", e);
            }
            return filterParamStr;
        }
    
        /**
         * <一句话功能简述> 处理过滤参数
         * <功能详细描述> 
         * author: zhanggw
         * 创建时间:  2021/10/12
         */
        private static String processFilterParam(String filterName, String filterValue) {
            try{
                // 去掉单引号和空格
                filterValue = filterValue.replace("'","");
                filterValue = filterValue.trim();
    
                // 处理日期字段
                if(FIELD_DATE_LIST.contains(filterName)){
                    if("0".equals(filterValue)){ // 时间为0表示空
                        return "";
                    }
    
                    if(StringUtils.isNotBlank(filterValue)){ // 由于存入es中的时间字符串没加时区,默认不是东八区,查询时间参数需延后8小时
                        Date dateVal = new Date();
                        dateVal.setTime(Long.parseLong(filterValue));
                        logger.trace("dateVal:{}", dateVal);
                        dateVal = DateUtils.timeCalendar(dateVal, 8, 0, 0);
                        logger.trace("dateVal:{}", dateVal);
                        filterValue = dateVal.getTime()+"";
                        return filterValue;
                    }
                }
            }catch (Exception e){
                logger.error("处理过滤器参数异常!");
            }
            return filterValue;
        }
    
        /**
         * <一句话功能简述> 模糊搜索参数转化
         * <功能详细描述> 
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param searchParamBasic 模糊搜索参数 is_active:'2'
         */
        private static QueryBuilder getMatchQuery(String searchParamBasic) {
            try{
                if(StringUtils.isBlank(searchParamBasic)){
                    return null;
                }
                int separateIndex = searchParamBasic.indexOf(":");
                String fieldName = camelCaseName(searchParamBasic.substring(0, separateIndex));
                String fieldValue = searchParamBasic.substring(separateIndex);
                fieldValue = fieldValue.replace("'","").replace(":","");
                fieldName = fieldName.trim().replace("(","");
                fieldValue = fieldValue.trim().replace(")","");
                logger.debug("searchParamBasic:{},fieldName:{},fieldValue:{}", searchParamBasic, fieldName, fieldValue);
    
                MatchQueryBuilder matchQueryBuilder = null;
                if(fieldValue.contains("^")){
                    try{
                        String[] valueArray = fieldValue.split("\\^");
                        matchQueryBuilder = QueryBuilders.matchQuery(fieldName, valueArray[0]);
                        matchQueryBuilder.boost(Integer.parseInt(valueArray[1]));
                    }catch (Exception e){
                        logger.error("elasticSearch boost设置异常!");
                        String[] valueArray = fieldValue.split("\\^");
                        matchQueryBuilder = QueryBuilders.matchQuery(fieldName, valueArray[0]);
                    }
                }else{
                    matchQueryBuilder = QueryBuilders.matchQuery(fieldName, fieldValue);
                }
    
                return matchQueryBuilder;
            }catch (Exception e){
                logger.error("getMatchQuery error!", e);
            }
            return null;
        }
    
        /**
         * <一句话功能简述> 精确搜索参数转化
         * <功能详细描述>
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param termParamBasic 模糊搜索参数 is_active:'2'
         */
        private static QueryBuilder getTermQuery(String termParamBasic) {
            try{
                if(StringUtils.isBlank(termParamBasic)){
                    return null;
                }
                int separateIndex = termParamBasic.indexOf(":");
                String fieldName = camelCaseName(termParamBasic.substring(0, separateIndex));
                String fieldValue = termParamBasic.substring(separateIndex);
                fieldValue = fieldValue.replace("'","").replace(":","");
                fieldName = fieldName.trim();
                fieldValue = fieldValue.trim();
                logger.trace("termParamBasic:{},fieldName:{},fieldValue:{}", termParamBasic, fieldName, fieldValue);
                return QueryBuilders.termQuery(fieldName, fieldValue);
            }catch (Exception e){
                logger.error("getTermQuery error!", e);
            }
            return null;
        }
    
        /**
         * <一句话功能简述> 含下划线字符串转换为驼峰式字符串
         * <功能详细描述> 
         * author: zhanggw
         * 创建时间:  2021/9/27
         */
        public static String camelCaseName(String underscoreName) {
            if(StringUtils.isBlank(underscoreName) || !underscoreName.contains("_")){
                return underscoreName;
            }
    
            StringBuilder result = new StringBuilder();
            boolean flag = false;
            for (int i = 0; i < underscoreName.length(); i++) {
                char ch = underscoreName.charAt(i);
                if ("_".charAt(0) == ch) {
                    flag = true;
                } else {
                    if (flag) {
                        result.append(Character.toUpperCase(ch));
                        flag = false;
                    } else {
                        result.append(ch);
                    }
                }
            }
            return result.toString();
        }
        
        /**
         * <一句话功能简述> 查询添加排序参数
         * <功能详细描述> 
         * author: zhanggw
         * 创建时间:  2021/9/27
         * @param sortStr pay_amount:DECREASE;shelves_date:DECREASE
         */
        private static void queryAddSort(SearchSourceBuilder sourceBuilder, String sortStr) {
            try{
                if(StringUtils.isBlank(sortStr)){
                    return;
                }
    
                String[] sortArray = sortStr.split(";");
                if(sortArray.length > 0){
                    for(String sortSubParam:sortArray){
                        String[] sortSubParamArray = sortSubParam.split(":");
                        String sortFieldName = sortSubParamArray[0];
                        String fieldValue = sortSubParamArray[1];
                        SortOrder sortOrder = SortOrder.DESC; // 默认降序 DECREASE
                        if("INCREASE".equals(fieldValue)){
                            sortOrder = SortOrder.ASC;
                        }
    
                        if("_score".equalsIgnoreCase(sortFieldName)){ // 指定评分排序
                            sourceBuilder.sort(new FieldSortBuilder("_score").order(sortOrder));
                        }else{ // 非评分排序会进行驼峰转换
                            String fieldName = camelCaseName(sortFieldName);
                            sourceBuilder.sort(new FieldSortBuilder(fieldName).order(sortOrder));
                        }
                    }
                }
            }catch (Exception e){
                logger.error("查询添加排序参数异常!", e);
            }
        }
    
        public static void main(String[] args) {
            String query = "{\"dataAmount\":\"24\",\"andFilter\":\"display_start_date<=1634017236255,(display_end_date>=1634017236255 OR display_end_date=0),\",\"searchParam\":\"company_id:'020001015880652390500000' AND goods_class:'110000' AND is_active:'2' AND item_state:'6'\",\"dataStart\":\"0\",\"sort\":\"seven_sales:DECREASE;shelves_date:DECREASE\"}";
            query = "{\"dataAmount\":\"10\",\"andFilter\":\"display_start_date<=1634022646464,(display_end_date>=1634022646464 OR display_end_date=0),\",\"searchParam\":\"default:'1090' AND is_active:'2' AND item_type:'2' AND item_state:'6'\",\"dataStart\":\"0\",\"sort\":\"pay_amount:DECREASE;shelves_date:DECREASE\"}";
            query = "{\"dataAmount\":\"6\",\"andFilter\":\"info_state=5\",\"searchParam\":\"(default:'测试' OR info_name:'测试' OR company_name:'测试' OR info_content:'测试')\",\"dataStart\":\"0\",\"sort\":\"is_top:DECREASE;refresh_date:DECREASE;pass_date:DECREASE\",\"showFields\":\"info_id,info_name,info_type,second_type,start_date,end_date,province,city,region,address,info_banner,info_content,info_picture,info_url,contact_info,enroll_type,invite_type,info_state,fail_reasion,company_id,company_name,company_abbr,company_logo,company_type,user_id,enroll_num,scan_num,pass_date,modify_date,create_date,remarks,is_top,refresh_date,user_type\"}";
            query = "{\"dataAmount\":\"6\",\"andFilter\":\"info_state=5\",\"searchParam\":\"(default:'测试'^30 OR info_name:'测试'^100 OR company_name:'测试'^80 OR info_content:'测试'^10)\",\"dataStart\":\"0\",\"sort\":\"is_top:DECREASE;refresh_date:DECREASE;pass_date:DECREASE\",\"showFields\":\"info_id,info_name,info_type,second_type,start_date,end_date,province,city,region,address,info_banner,info_content,info_picture,info_url,contact_info,enroll_type,invite_type,info_state,fail_reasion,company_id,company_name,company_abbr,company_logo,company_type,user_id,enroll_num,scan_num,pass_date,modify_date,create_date,remarks,is_top,refresh_date,user_type\"}";
            SearchSourceBuilder searchSourceBuilder = generateEsQuery(JSON.parseObject(query));
            logger.debug("searchSourceBuilder:{}", searchSourceBuilder);
        }
    
    }
    

        运行main方法生成的es查询语句为:

    {
    	"from": 0,
    	"size": 10,
    	"query": {
    		"bool": {
    			"must": [{
    				"bool": {
    					"should": [{
    						"match": {
    							"platformType": {
    								"query": "1 ",
    								"operator": "OR",
    								"prefix_length": 0,
    								"max_expansions": 50,
    								"fuzzy_transpositions": true,
    								"lenient": false,
    								"zero_terms_query": "NONE",
    								"auto_generate_synonyms_phrase_query": true,
    								"boost": 1.0
    							}
    						}
    					}, {
    						"match": {
    							" platformType": {
    								"query": "3",
    								"operator": "OR",
    								"prefix_length": 0,
    								"max_expansions": 50,
    								"fuzzy_transpositions": true,
    								"lenient": false,
    								"zero_terms_query": "NONE",
    								"auto_generate_synonyms_phrase_query": true,
    								"boost": 1.0
    							}
    						}
    					}],
    					"adjust_pure_negative": true,
    					"boost": 1.0
    				}
    			}, {
    				"match": {
    					"default": {
    						"query": "5473",
    						"operator": "OR",
    						"prefix_length": 0,
    						"max_expansions": 50,
    						"fuzzy_transpositions": true,
    						"lenient": false,
    						"zero_terms_query": "NONE",
    						"auto_generate_synonyms_phrase_query": true,
    						"boost": 1.0
    					}
    				}
    			}, {
    				"match": {
    					"isActive": {
    						"query": "2",
    						"operator": "OR",
    						"prefix_length": 0,
    						"max_expansions": 50,
    						"fuzzy_transpositions": true,
    						"lenient": false,
    						"zero_terms_query": "NONE",
    						"auto_generate_synonyms_phrase_query": true,
    						"boost": 1.0
    					}
    				}
    			}, {
    				"match": {
    					"itemType": {
    						"query": "2",
    						"operator": "OR",
    						"prefix_length": 0,
    						"max_expansions": 50,
    						"fuzzy_transpositions": true,
    						"lenient": false,
    						"zero_terms_query": "NONE",
    						"auto_generate_synonyms_phrase_query": true,
    						"boost": 1.0
    					}
    				}
    			}, {
    				"bool": {
    					"should": [{
    						"match": {
    							"itemState": {
    								"query": "6 ",
    								"operator": "OR",
    								"prefix_length": 0,
    								"max_expansions": 50,
    								"fuzzy_transpositions": true,
    								"lenient": false,
    								"zero_terms_query": "NONE",
    								"auto_generate_synonyms_phrase_query": true,
    								"boost": 1.0
    							}
    						}
    					}, {
    						"match": {
    							" itemState": {
    								"query": "7",
    								"operator": "OR",
    								"prefix_length": 0,
    								"max_expansions": 50,
    								"fuzzy_transpositions": true,
    								"lenient": false,
    								"zero_terms_query": "NONE",
    								"auto_generate_synonyms_phrase_query": true,
    								"boost": 1.0
    							}
    						}
    					}],
    					"adjust_pure_negative": true,
    					"boost": 1.0
    				}
    			}],
    			"filter": [{
    				"range": {
    					"minAmount": {
    						"from": null,
    						"to": "50",
    						"include_lower": true,
    						"include_upper": true,
    						"boost": 1.0
    					}
    				}
    			}, {
    				"range": {
    					"displayStartDate": {
    						"from": null,
    						"to": "1632728060134",
    						"include_lower": true,
    						"include_upper": true,
    						"boost": 1.0
    					}
    				}
    			}, {
    				"bool": {
    					"should": [{
    						"bool": {
    							"must_not": [{
    								"exists": {
    									"field": "displayEndDate",
    									"boost": 1.0
    								}
    							}],
    							"adjust_pure_negative": true,
    							"boost": 1.0
    						}
    					}, {
    						"range": {
    							" displayEndDate": {
    								"from": "1632728060134",
    								"to": null,
    								"include_lower": true,
    								"include_upper": true,
    								"boost": 1.0
    							}
    						}
    					}],
    					"adjust_pure_negative": true,
    					"boost": 1.0
    				}
    			}],
    			"adjust_pure_negative": true,
    			"boost": 1.0
    		}
    	},
    	"sort": [{
    		"payAmount": {
    			"order": "desc"
    		}
    	}, {
    		"shelvesDate": {
    			"order": "desc"
    		}
    	}]
    }

    使用kibana运行es查询语句

    展开全文
  • 还记得之前的简单查询: 指定id查询 get world/persion/IpheZHEB1uk_PYXuZvA- 指定id查询,检索指定内容 get world/persion/IpheZHEB1uk_PYXuZvA-?...GET _search { "query" : { "match_all" : { ...

    还记得之前的简单查询:

    指定id查询
    get world/persion/IpheZHEB1uk_PYXuZvA-
    指定id查询,检索指定内容
    get world/persion/IpheZHEB1uk_PYXuZvA-?_source=name,sex

    下面是比较常见的完整一些的查询方法:

    1.查询所有

    GET _search
    {
    	"query" : {
    		"match_all" : {
    		
    		}
    	}
    }
    单一个_search查询就是在所有库中的数据里进行查询(可以拼接索引库如下:)
    
    GET world/_search
    {
    	"query" : {
    		"match_all" : {
    		
    		}
    	},
    	"_source": ["name","sex"]
    }
    
    "_source": ["字段","字段2",....]
    这里的字段看需要自行拼接,查出来的数据是只包含所给字段的信息内容
    

    2.关键字查询

    GET world/_search
    {
      "query": {
        "match": {
          "name": "jack"
        }
      }
    }
    

    数据如下:

    因为name的数据类型是text支持分词,查询的只要是与jack相似的就都会查出来

    在这里插入图片描述
    3.复合查询

    3.1must(交集)

    详细解释一下:
    query:查找
    bool:多条件拼凑
    must:需要的数据的字段名
    must_not不需要的数据的字段名

    GET world/_search
    {
      "query": {
        "bool": {
          "must": [
          	{
          	  "match": {
          	    "name": "jack"
          	  }
          	}
          ],
          "must_not": [
            {
              "match": {
                "age": "19"
              }
            }
          ]
        }
      }
    }
    

    数据查询出来长这样:

    在这里插入图片描述

    3.2should(并集)

    GET world/_search
    {
      "query": {
        "bool": {
          "should": [
            {
              "match": {
                "name": "jack"
              }
            },
            {
              "match": {
                "age": "15"
              }
            }
          ]
        }
      }
    }
    

    数据解析:

    在这里插入图片描述
    4.精准查询

    精准查询指定数据类型(数值、布尔、未分词字符串)

    GET world/_search
    {
      "query": {
        "term" : {
        	"age":{
    			"value" : 15
    		}
        }
      }
    }
    
    数据展示:

    在这里插入图片描述
    5.范围查询

    GET 索引库/_search
    {
      "query": {
        "range": {
          "字段": {
            gt : "大于",
            lt : "小于",
            gte : "大于或等于",
            lte : "小于或等于" 
          }
        }
      }
    }
    
    GET world/_search
    {
      "query": {
        "range": {
          "age": {
            "gte": 16,
            "lte": 19
          }
        }
      }
    }
    

    数据解析:

    在这里插入图片描述
    6.排序(和数据库类似)

    GET czxy/_search
    {
      "query": {
        "match_all": {
        }
      },
      "sort" : {
      	"字段": {
      		"order" : "排序"				//asc 、desc
      	}
      }
    }
    
    #查询所有,然后排序
    GET world/_search
    {
      "query": {
        "match_all": {}
      },
      "sort": [
        {
          "age": {
            "order": "desc"
          }
        }
      ]
    }
    

    数据内容:

    在这里插入图片描述
    7.分页查询

    GET czxy/_search
    {
      "query": {
        "match_all": {
        }
      },
      "from" : 0,			//开始索引号,从0开始的
      "size" : 2			//每页的个数
    }
    
    GET world/_search
    {
      "query": {
        "match_all": {}
      },
      "from": 1,
      "size": 2
      
    }
    

    数据展示:

    在这里插入图片描述

    在这里插入图片描述

    展开全文
  • elasticsearch查询语句

    2020-12-20 16:07:59
    1. es 查询排序 首先排序字段必须为 date 或 integer 类型,其他类型不可排序,具体使用语句: GET zhifou/doc/_search { "query": { "match_all": {} }, "sort": [ { "age": { "order": "asc" } } ] } ...
    1. es 查询排序

    首先排序字段必须为 date 或 integer 类型,其他类型不可排序,具体使用语句:

    GET zhifou/doc/_search
    {
      "query": {
        "match_all": {}
      },
      "sort": [
        {
          "age": {
            "order": "asc"
          }
        }
      ]
    }
    

    参考: https://www.cnblogs.com/heshun/articles/10657327.html

    2. es 常用 curl 语句

    使用curl命令操作elasticsearch And 使用http 查询ES

    展开全文
  • 超全的elasticsearch查询语句语法大全

    千次阅读 2020-10-16 17:11:40
    es是什么? es是基于Apache Lucene的开源分布式(全文)搜索引擎,,提供简单的RESTful API来隐藏Lucene的复杂性。...Relational DB Elasticsearch 数据库(database) 索引(indices) 表(tables) types 行(rows
  • es查询语句

    2020-06-23 19:55:05
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1t8BEStV-1592913263205)(C:\Users\lvcky2333\AppData\Roaming\Typora\typora-user-images\image-20200623170216177.png)] ...get 查询 - G
  • ElasticSearch 常用的查询语句

    千次阅读 2021-03-13 15:21:05
    使用ES时候发现了一篇挺好的文章,收集下来分享给大家。Filter DSLterm 过滤term主要用于精确匹配哪些值,比如数字,日期,布尔值或 not_analyzed 的字符串(未经分析的文本数据类型):{ "term": { "age": 26 }}{ ...
  • 常用mysql语句elasticsearch查询语句

    千次阅读 2018-10-08 15:04:41
    多个查询条件 bool(must、should、must_not) select * from index_person where name = 'jeck' or sex = 'male' order by age,sex { "query":{ "bool":{ "should":{ {&...
  • ES查询语句

    千次阅读 2019-09-05 10:54:16
    1.通配符查询KEYWORD字段(不会建分词索引,会建索引) { “query”: { “bool”:{ “filter”:{“wildcard”:{“sourceMode”:“Desktop.rar”}}} } }
  • 学习elasticsearch的时候,想要查看elasticsearch发送的DSL语句,可以添加如下配置 一、配置RestHighLevelClient /** * @author wfd * @description * @create 2021/3/7 23:10 */ @Configuration public class ...
  • 1、查看所有index(类似mysql的database) ...http://192.168.194.16:9200/elastic_segment-20211201/_search 3、获取所有index的结构 http://localhost:9200/_mapping?pretty=true http://localhost:9200/index/typ
  • Elasticsearch 作为一个文档型数据库,和mysql等关系型数据库一样,同样有相关的查询语法和常用的查询语句 1.查询所有数据 GET /索引名/_search { "query": { "match_all": {} } } 2.根据关键字查询 GET /索引...
  • ElasticSearch ES+java常用查询语句

    万次阅读 2018-09-05 14:38:32
    elasticsearch 用JAVA 查询数据太多,一次性返回数据有限制,  用车架号分组返回数据的时候,一直误认为.setFrom(0).setSize(100)就是查询返回的数据,这样的语句在单查询的时候没有问题,但是在addAggregation ...
  • es基本语句详解 查询语句详解

    千次阅读 2021-07-28 15:43:38
    es基本语句详解 查询语句详解声明Rest风格索引的基本操作1. 创建一个索引2. 查看索引 我们使用elasticsearch-head3. 删除索引其它命令==文档的基本操作(重点)==添加数据修改文档删除文档查找(重重重点)通过id...
  • 查询表达式转变为elasticsearch查询语句
  • 查询语句中包含must与should的时候,发现should失效。那我们就把must改成must_not,逻辑再取反就可以了(无意中发现)。 希望能帮到大家,真TM有趣~ 贴俩真实语句给大家看看把。 失败语句: { "from" : 0...
  • ElasticSearch的API, DSL查询语句 文章目录ElasticSearch的API, DSL查询语句一、保存数据1.新增数据2.更新操作3.更新的同时增加属性4.批量操作二、查询数据1.查询DSL2.返回部分字段3.match精确匹配查询4.字符串,多...
  • elasticsearch查询语句

    千次阅读 2017-05-01 22:44:08
    1.ElasticSearch基本概念elasticsearch基本概念见:https://es.xiaoleilu.com/010_Intro/05_What_is_it.html 集群模式安装:http://blog.csdn.net/cweeyii/article/details/710558842. 重点概念 搜素类型...
  • spring data elasticsearch 打印查询语句

    千次阅读 2020-09-15 15:02:20
    在使用 spring data elasticsearch 操作 elasticsearch 查询语句默认是不显示的,我们 在开发调试阶段想要像Mybatis那样打印SQL该如何做呢? 说明: 我这里的springboot版本 是 2.1.6.RELEASE elasticsearch 版本为...
  • //起手构建请求 SearchRequest request = new SearchRequest(); request常用操作: 指定索引,可传入多个索引,支持通配符* request.indices(String[] tables) 等同于 select xx from table1,table2… ...分页查询
  • 分享一个大牛的人工智能教程。...GET /bookdb_index/book/_search?q=guide #查询任一字段包含guide的记录。 下面是完整body版的查询: { "query": { "multi_match": { "query": "guide", "fiel
  • 我用的是idea的elasticsearch插件,学习es怎么用 一、安装 我用的公司的,自己要用就去装本地的es 二、语句 1、创建 //创建索引(类似于sql里的建表) //文档规定文档类型(添加数据) PUT /addtest/...
  • es查询语句,term和match的区别

    千次阅读 2021-12-03 15:06:57
    es查询特定的数据 curl -H “Content-Type: application/json” --user es账号:es密码 -XGET “http://ip:9200/索引/_search?pretty” -d’{ “query”: { “term”: { “idCardNo”: { “value”: “要查询的...
  • Kibana操作es查询语句

    千次阅读 2019-12-10 11:41:48
    1.查询所有 GET 索引名/_search { "query": { "match_all": {} } } 2.查看mapping GET 索引名/_mapping 3.查看别名 GET 索引名/_alias
  • 这次是记录ElasticSearch6的一些高级查询语句 目录 1.查询当前所有类型的文档 2.根据ID来查询数据 3.根据多个ID进行批量查询 4.有查询条件的语句查询 1.查询一个精准的条件 2.查询一个范围类型 3.对查询到的...
  • Elasticsearch-PHP进行查询语句封装 可实现链式调用 方便 es查询
  • 之前谈过Elasticsearch的介绍,还有服务端和客户端的使用,这一篇该到重点了---查询语句。正所谓--无搜索,无Elasticsearch,至少,我是这么认为的。那么,ES的搜索语句有哪些呢?其实,它们比你想象中的多! 一.全...
  • es常用查询语句

    2022-01-06 20:58:48
    1.注入es查询模板类 // 使用注解 @RequiredArgsConstructor private final ElasticsearchRestTemplate elasticsearchRestTemplate; 2.查询示例代码 long startTime = LocalDateTime.of(totalTime.toLocalDate()....
  • #获取ES所有索引 GET _cat/indices #创建索引 PUT task_info #创建索引文档结构 PUT task_info/_mapping { "properties": { "robotName":{ "type": "text", "fielddata": true, "fields": { "raw":...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 84,614
精华内容 33,845
关键字:

es查询语句

友情链接: perceptron.rar.rar