ElasticSearch 常用的结构化查询字符串(持续更新中...)

来源:互联网 发布:ubuntu c 开发 编辑:程序博客网 时间:2024/06/11 18:54

终于是有些了解 ElasticSearch 的结构化查询字符串了,通过代码做了一些整理,有助于对比理解。

/** * ElasticSearch 常用的结构化查询字符串。 */public class ElasticSearchQuerys {    /**     * 查询。     * <pre>     * query(matchAll()) 的返回结果:     *     * {     *   "query" : {     *       "match_all" : { }     *   }     * }     * </pre>     */    public static String query(String queryString) {        return new SearchSourceBuilder().query(queryString).toString();    }    /**     * 匹配全部。     * <pre>     * {     *   "match_all" : { }     * }     * </pre>     */    public static String matchAll() {        return new MatchAllQueryBuilder().toString();    }    /**     * 匹配全部。     * <pre>     * matchAll(1.2f) 的返回结果:     *     * {     *   "match_all" : {     *       "boost" : 1.2     *   }     * }     * </pre>     *     * @param boost     * @return     */    public static String matchAll(float boost) {        return new MatchAllQueryBuilder().boost(boost).toString();    }    /**     * 匹配单个字段。     * <pre>     * match("message", "this is a text") 的返回结果:     *     * {     *   "match" : {     *     "message" : {     *       "query" : "this is a text",     *       "operator" : "AND"     *     }     *   }     * }     * </pre>     *     * @param field 字段名     * @param text 匹配的文本,文本会被分词     * @return 查询字符串     */    public static String match(String field, Object text) {        return new MatchQueryBuilder(field, text).operator(Operator.AND).toString();    }    /**     * 匹配多字段。     * <pre>     * matchMulti("this is a text", "subject", "message") 的返回结果:     *     * {     *   "multi_match" : {     *     "query" : "this is a text",     *     "fields" : [ "subject", "message" ]     *   }     * }     * </pre>     *     * @param text 匹配的文本,文本会被分词     * @param field 必须字段     * @param fields 可以选字段     * @return     */    public static String matchMulti(Object text, String field, String... fields) {        if (fields == null || fields.length == 0) {            return match(field, text);        }        String[] newFields = new String[fields.length + 1];        newFields[0] = field;        System.arraycopy(fields, 0, newFields, 1, fields.length);        return new MultiMatchQueryBuilder(text, newFields).toString();    }    /**     * 完全匹配值。     * <pre>     * term("user", "Kimchy") 的返回结果:     *     * {     *   "term" : {     *     "user" : "Kimchy"     *   }     * }     * </pre>     *     * @param field     * @param value     * @return     */    public static String term(String field, Object value) {        return new TermQueryBuilder(field, value).toString();    }}