您的位置:首页 > 其它

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

2017-12-22 21:23 344 查看
终于是有些了解 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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: