flagList = Lists.newLinkedList();
125 | for (String flag : flags) {
126 | flagList.add(SimpleQueryStringFlag.valueOf(flag.toUpperCase()));
127 | }
128 | simpleStringQuery.flags(flagList.toArray(new SimpleQueryStringFlag[0]));
129 | }
130 |
131 |
132 | if (extraParamMap.containsKey(ElasticConstants.DEFAULT_OPERATOR)) {
133 | String val = extraParamMap.get(ElasticConstants.DEFAULT_OPERATOR);
134 |
135 | if (ElasticConstants.AND.equalsIgnoreCase(val)) {
136 | simpleStringQuery.defaultOperator(Operator.AND);
137 | }
138 | if (ElasticConstants.OR.equalsIgnoreCase(val)) {
139 | simpleStringQuery.defaultOperator(Operator.OR);
140 | }
141 | }
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/join/HasChildQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.join;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlMethodInvokeHelper;
7 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodQueryParser;
10 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.BoolExpressionParser;
11 | import org.apache.lucene.search.join.ScoreMode;
12 | import org.elasticsearch.index.query.BoolQueryBuilder;
13 | import org.elasticsearch.join.query.HasChildQueryBuilder;
14 | import org.elasticsearch.join.query.JoinQueryBuilders;
15 |
16 |
17 | import java.util.List;
18 |
19 | /**
20 | * has_child(childType, filterExpression, minChildren, maxChildren)
21 | *
22 | * has_child('collection_plan', principal > 1000)
23 | *
24 | * has_child('collection_plan', principal > 1000, 1, 4)
25 | */
26 | public class HasChildQueryParser implements MethodQueryParser {
27 |
28 | private static List HAS_CHILD_METHOD = ImmutableList.of("has_child", "hasChild", "has_child_query", "hasChildQuery");
29 |
30 | @Override
31 | public List defineMethodNames() {
32 | return HAS_CHILD_METHOD;
33 | }
34 |
35 | @Override
36 | public boolean isMatchMethodInvocation(MethodInvocation invocation) {
37 | return ElasticSqlMethodInvokeHelper.isMethodOf(defineMethodNames(), invocation.getMethodName());
38 | }
39 |
40 | @Override
41 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
42 | if (invocation.getParameterCount() != 2 && invocation.getParameterCount() != 4) {
43 | throw new ElasticSql2DslException(
44 | String.format("[syntax error] There's no %s args method named [%s].",
45 | invocation.getParameterCount(), invocation.getMethodName()));
46 | }
47 | }
48 |
49 | @Override
50 | public AtomicQuery parseMethodQuery(MethodInvocation invocation) throws ElasticSql2DslException {
51 | String childType = invocation.getParameterAsString(0);
52 | SQLExpr filter = invocation.getParameter(1);
53 |
54 | BoolExpressionParser boolExpressionParser = new BoolExpressionParser();
55 | String queryAs = invocation.getQueryAs();
56 |
57 | BoolQueryBuilder filterBuilder = boolExpressionParser.parseBoolQueryExpr(filter, queryAs);
58 | HasChildQueryBuilder hasChildQueryBuilder = JoinQueryBuilders.hasChildQuery(childType, filterBuilder, ScoreMode.None);
59 |
60 | if (invocation.getParameterCount() == 4) {
61 | Long minChildren = invocation.getParameterAsLong(2);
62 | Long maxChildren = invocation.getParameterAsLong(3);
63 |
64 | hasChildQueryBuilder.minMaxChildren(minChildren.intValue(), maxChildren.intValue());
65 | }
66 |
67 | return new AtomicQuery(hasChildQueryBuilder);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/join/HasParentQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.join;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlMethodInvokeHelper;
7 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodQueryParser;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
10 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.BoolExpressionParser;
11 | import org.elasticsearch.index.query.BoolQueryBuilder;
12 | import org.elasticsearch.join.query.HasParentQueryBuilder;
13 | import org.elasticsearch.join.query.JoinQueryBuilders;
14 |
15 | import java.util.List;
16 |
17 | /**
18 | * has_parent(parentType, filterExpression)
19 | *
20 | * has_parent('investment', principal > 100 and status='SUCCESS')
21 | *
22 | */
23 | public class HasParentQueryParser implements MethodQueryParser {
24 |
25 | private static List HAS_PARENT_METHOD = ImmutableList.of("has_parent", "hasParent", "has_parent_query", "hasParentQuery");
26 |
27 | @Override
28 | public List defineMethodNames() {
29 | return HAS_PARENT_METHOD;
30 | }
31 |
32 | @Override
33 | public boolean isMatchMethodInvocation(MethodInvocation invocation) {
34 | return ElasticSqlMethodInvokeHelper.isMethodOf(defineMethodNames(), invocation.getMethodName());
35 | }
36 |
37 | @Override
38 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
39 | if (invocation.getParameterCount() != 2) {
40 | throw new ElasticSql2DslException(
41 | String.format("[syntax error] There's no %s args method named [%s].",
42 | invocation.getParameterCount(), invocation.getMethodName()));
43 | }
44 | }
45 |
46 | @Override
47 | public AtomicQuery parseMethodQuery(MethodInvocation invocation) throws ElasticSql2DslException {
48 | String parentType = invocation.getParameterAsString(0);
49 | SQLExpr filter = invocation.getParameter(1);
50 |
51 | BoolExpressionParser boolExpressionParser = new BoolExpressionParser();
52 | String queryAs = invocation.getQueryAs();
53 |
54 | BoolQueryBuilder filterBuilder = boolExpressionParser.parseBoolQueryExpr(filter, queryAs);
55 | HasParentQueryBuilder hasParentQueryBuilder = JoinQueryBuilders.hasParentQuery(parentType, filterBuilder, false);
56 |
57 | return new AtomicQuery(hasParentQueryBuilder);
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/join/JoinQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.join;
2 |
3 | import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodQueryParser;
9 |
10 | import java.util.List;
11 |
12 | public class JoinQueryParser {
13 |
14 | private final List joinQueryParsers;
15 |
16 | public JoinQueryParser() {
17 | joinQueryParsers = ImmutableList.of(
18 | new HasParentQueryParser(),
19 | new HasChildQueryParser()
20 | );
21 | }
22 |
23 | public Boolean isJoinAtomQuery(MethodInvocation invocation) {
24 | return joinQueryParsers.stream().anyMatch(methodQueryParser -> methodQueryParser.isMatchMethodInvocation(invocation));
25 | }
26 |
27 | public AtomicQuery parseJoinAtomQuery(SQLMethodInvokeExpr methodQueryExpr, String queryAs) {
28 | MethodInvocation methodInvocation = new MethodInvocation(methodQueryExpr, queryAs);
29 | MethodQueryParser joinAtomQueryParser = getQueryParser(methodInvocation);
30 | joinAtomQueryParser.checkMethodInvocation(methodInvocation);
31 | return joinAtomQueryParser.parseMethodQuery(methodInvocation);
32 | }
33 |
34 | private MethodQueryParser getQueryParser(MethodInvocation methodInvocation) {
35 | for (MethodQueryParser joinQueryParserItem : joinQueryParsers) {
36 | if (joinQueryParserItem.isMatchMethodInvocation(methodInvocation)) {
37 | return joinQueryParserItem;
38 | }
39 | }
40 | throw new ElasticSql2DslException(
41 | String.format("[syntax error] Can not support join query expr[%s] condition",
42 | methodInvocation.getMethodName()));
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/mapping/MappingQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.mapping;
2 |
3 |
4 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
5 | import org.apache.commons.lang3.StringUtils;
6 | import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsRequest;
7 | import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
8 |
9 | /**
10 | * @author iamazy
11 | * @date 2019/5/5
12 | * @descrition
13 | **/
14 | public class MappingQueryParser {
15 |
16 | public static Object parse(String sql) {
17 | String[] descItems = StringUtils.split(sql, " ");
18 | GetFieldMappingsRequest getFieldMappingsRequest = new GetFieldMappingsRequest();
19 | GetMappingsRequest getMappingsRequest = new GetMappingsRequest();
20 | if (descItems.length == 2) {
21 | String[] items = descItems[1].split("/");
22 | switch (items.length) {
23 | case 2: {
24 | getFieldMappingsRequest.indices(items[0]);
25 | getFieldMappingsRequest.fields(items[1]);
26 | return getFieldMappingsRequest;
27 | }
28 | case 1:
29 | default: {
30 | getMappingsRequest.indices(items[0]);
31 | return getMappingsRequest;
32 | }
33 | }
34 | } else {
35 | throw new ElasticSql2DslException("[syntax error] desc must have table name or table/field name");
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/score/BoostingQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.score;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLNumberExpr;
5 | import com.google.common.collect.ImmutableList;
6 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
7 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlMethodInvokeHelper;
8 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
10 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodQueryParser;
11 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.BoolExpressionParser;
12 | import org.elasticsearch.index.query.BoolQueryBuilder;
13 | import org.elasticsearch.index.query.BoostingQueryBuilder;
14 | import org.elasticsearch.index.query.QueryBuilders;
15 |
16 | import java.util.List;
17 |
18 | /**
19 | * @author iamazy
20 | * @date 2019/4/9
21 | * @descrition
22 | **/
23 | public class BoostingQueryParser implements MethodQueryParser {
24 |
25 | private static List BOOSTING_METHOD = ImmutableList.of("boosting");
26 |
27 | @Override
28 | public AtomicQuery parseMethodQuery(MethodInvocation invocation) throws ElasticSql2DslException {
29 |
30 | SQLExpr positiveExpr = invocation.getParameter(0);
31 | SQLExpr negativeExpr=invocation.getParameter(1);
32 | Float negativeBoost=((SQLNumberExpr) invocation.getParameter(2)).getNumber().floatValue();
33 | BoolExpressionParser boolExpressionParser = new BoolExpressionParser();
34 | BoolQueryBuilder positiveQuery = boolExpressionParser.parseBoolQueryExpr(positiveExpr, invocation.getQueryAs());
35 | BoolQueryBuilder negativeQuery=boolExpressionParser.parseBoolQueryExpr(negativeExpr,invocation.getQueryAs());
36 | BoostingQueryBuilder boostingQueryBuilder = QueryBuilders.boostingQuery(positiveQuery,negativeQuery).negativeBoost(negativeBoost);
37 | AtomicQuery atomicQuery= new AtomicQuery(boostingQueryBuilder);
38 | atomicQuery.getHighlighter().addAll(boolExpressionParser.getHighlighter());
39 | return atomicQuery;
40 |
41 | }
42 |
43 | @Override
44 | public List defineMethodNames() {
45 | return BOOSTING_METHOD;
46 | }
47 |
48 | @Override
49 | public boolean isMatchMethodInvocation(MethodInvocation invocation) {
50 | return ElasticSqlMethodInvokeHelper.isMethodOf(defineMethodNames(), invocation.getMethodName());
51 | }
52 |
53 | @Override
54 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
55 | if (invocation.getParameterCount() != 3) {
56 | throw new ElasticSql2DslException(
57 | String.format("[syntax error] There's no %s args method named [%s].",
58 | invocation.getParameterCount(), invocation.getMethodName()));
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/score/ScoreQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.score;
2 |
3 | import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodQueryParser;
9 | import lombok.Data;
10 |
11 | import java.util.List;
12 |
13 |
14 | /**
15 | * @author iamazy
16 | * @date 2019/4/9
17 | * @descrition
18 | **/
19 | @Data
20 | public class ScoreQueryParser {
21 |
22 | private final List scoreQueryParsers;
23 |
24 | public ScoreQueryParser() {
25 | scoreQueryParsers = ImmutableList.of(
26 | new BoostingQueryParser(),
27 | new FunctionScoreQueryParser()
28 | );
29 | }
30 |
31 | public Boolean isScoreAtomQuery(MethodInvocation invocation) {
32 | return scoreQueryParsers.stream().anyMatch(methodQueryParser -> methodQueryParser.isMatchMethodInvocation(invocation));
33 | }
34 |
35 | public AtomicQuery parseScoreAtomQuery(SQLMethodInvokeExpr methodQueryExpr, String queryAs) {
36 | MethodInvocation methodInvocation = new MethodInvocation(methodQueryExpr, queryAs);
37 | MethodQueryParser joinAtomQueryParser = getQueryParser(methodInvocation);
38 | joinAtomQueryParser.checkMethodInvocation(methodInvocation);
39 | return joinAtomQueryParser.parseMethodQuery(methodInvocation);
40 | }
41 |
42 | private MethodQueryParser getQueryParser(MethodInvocation methodInvocation) {
43 | for (MethodQueryParser scoreQueryParserItem : scoreQueryParsers) {
44 | if (scoreQueryParserItem.isMatchMethodInvocation(methodInvocation)) {
45 | return scoreQueryParserItem;
46 | }
47 | }
48 | throw new ElasticSql2DslException(
49 | String.format("[syntax error] Can not support score query expr[%s] condition",
50 | methodInvocation.getMethodName()));
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/script/ScriptQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.script;
2 |
3 | import com.google.common.collect.ImmutableList;
4 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
5 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
6 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.ParameterizedMethodQueryParser;
8 | import org.apache.commons.collections4.MapUtils;
9 | import org.apache.commons.lang3.StringUtils;
10 | import org.elasticsearch.index.query.QueryBuilders;
11 | import org.elasticsearch.script.Script;
12 |
13 | import java.util.List;
14 | import java.util.Map;
15 |
16 | public class ScriptQueryParser extends ParameterizedMethodQueryParser {
17 |
18 | private static List SCRIPT_METHOD = ImmutableList.of("script_query", "scriptQuery");
19 |
20 | @Override
21 | public List defineMethodNames() {
22 | return SCRIPT_METHOD;
23 | }
24 |
25 | @Override
26 | protected String defineExtraParamString(MethodInvocation invocation) {
27 | int extraParamIdx = 1;
28 |
29 | return (invocation.getParameterCount() == extraParamIdx + 1)
30 | ? invocation.getParameterAsString(extraParamIdx) : StringUtils.EMPTY;
31 | }
32 |
33 | @Override
34 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
35 | if (invocation.getParameterCount() != 1 && invocation.getParameterCount() != 2) {
36 | throw new ElasticSql2DslException(
37 | String.format("[syntax error] There's no %s args method named [%s].",
38 | invocation.getParameterCount(), invocation.getMethodName()));
39 | }
40 |
41 | String script = invocation.getParameterAsString(0);
42 | if (StringUtils.isEmpty(script)) {
43 | throw new ElasticSql2DslException("[syntax error] Script can not be blank!");
44 | }
45 | }
46 |
47 | @Override
48 | protected AtomicQuery parseMethodQueryWithExtraParams(MethodInvocation invocation, Map extraParamMap) throws ElasticSql2DslException {
49 | String script = invocation.getParameterAsString(0);
50 |
51 | if (MapUtils.isNotEmpty(extraParamMap)) {
52 | Map scriptParamMap = generateRawTypeParameterMap(invocation);
53 | return new AtomicQuery(QueryBuilders.scriptQuery(
54 | new Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG, script, scriptParamMap))
55 | );
56 | }
57 | return new AtomicQuery(QueryBuilders.scriptQuery(new Script(script)));
58 | }
59 |
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/FuzzyQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.cons.ElasticConstants;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.AbstractFieldSpecificMethodQueryParser;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
9 | import org.apache.commons.collections4.MapUtils;
10 | import org.apache.commons.lang3.StringUtils;
11 | import org.elasticsearch.common.unit.Fuzziness;
12 | import org.elasticsearch.index.query.FuzzyQueryBuilder;
13 | import org.elasticsearch.index.query.QueryBuilder;
14 | import org.elasticsearch.index.query.QueryBuilders;
15 |
16 | import java.util.List;
17 | import java.util.Map;
18 |
19 | public class FuzzyQueryParser extends AbstractFieldSpecificMethodQueryParser {
20 |
21 | private static final List FUZZY_QUERY_METHOD = ImmutableList.of("fuzzy", "fuzzy_query", "fuzzyQuery");
22 |
23 | FuzzyQueryParser() {
24 | super();
25 | }
26 |
27 | @Override
28 | public List defineMethodNames() {
29 | return FUZZY_QUERY_METHOD;
30 | }
31 |
32 | @Override
33 | public SQLExpr defineFieldExpr(MethodInvocation invocation) {
34 | return invocation.getParameter(0);
35 | }
36 |
37 | @Override
38 | protected String defineExtraParamString(MethodInvocation invocation) {
39 | int extraParamIdx = 2;
40 |
41 | return (invocation.getParameterCount() == extraParamIdx + 1)
42 | ? invocation.getParameterAsString(extraParamIdx) : StringUtils.EMPTY;
43 | }
44 |
45 | @Override
46 | public void checkMethodInvocation(MethodInvocation invocation) {
47 | if (invocation.getParameterCount() != 2 && invocation.getParameterCount() != 3) {
48 | throw new ElasticSql2DslException(
49 | String.format("[syntax error] There's no %s args method named [%s].",
50 | invocation.getParameterCount(), invocation.getMethodName()));
51 | }
52 |
53 | String text = invocation.getParameterAsString(1);
54 | if (StringUtils.isEmpty(text)) {
55 | throw new ElasticSql2DslException("[syntax error] Fuzzy search text can not be blank!");
56 | }
57 |
58 | if (invocation.getParameterCount() == 3) {
59 | String extraParamString = defineExtraParamString(invocation);
60 | if (StringUtils.isEmpty(extraParamString)) {
61 | throw new ElasticSql2DslException("[syntax error] The extra param of fuzzy method can not be blank");
62 | }
63 | }
64 | }
65 |
66 | @Override
67 | protected QueryBuilder buildQuery(MethodInvocation invocation, String fieldName, Map extraParams) {
68 | String text = invocation.getParameterAsString(1);
69 | FuzzyQueryBuilder fuzzyQuery = QueryBuilders.fuzzyQuery(fieldName, text);
70 |
71 | setExtraMatchQueryParam(fuzzyQuery, extraParams);
72 | return fuzzyQuery;
73 | }
74 |
75 | private void setExtraMatchQueryParam(FuzzyQueryBuilder fuzzyQuery, Map extraParamMap) {
76 | if (MapUtils.isEmpty(extraParamMap)) {
77 | return;
78 | }
79 | if (extraParamMap.containsKey(ElasticConstants.BOOST)) {
80 | String val = extraParamMap.get(ElasticConstants.BOOST);
81 | fuzzyQuery.boost(Float.valueOf(val));
82 | }
83 | if (extraParamMap.containsKey(ElasticConstants.TRANSPOSITIONS)) {
84 | String val = extraParamMap.get(ElasticConstants.TRANSPOSITIONS);
85 | fuzzyQuery.transpositions(Boolean.parseBoolean(val));
86 | }
87 | if (extraParamMap.containsKey(ElasticConstants.PREFIX_LENGTH)) {
88 | String val = extraParamMap.get(ElasticConstants.PREFIX_LENGTH);
89 | fuzzyQuery.prefixLength(Integer.valueOf(val));
90 | }
91 | if (extraParamMap.containsKey(ElasticConstants.MAX_EXPANSIONS)) {
92 | String val = extraParamMap.get(ElasticConstants.MAX_EXPANSIONS);
93 | fuzzyQuery.maxExpansions(Integer.valueOf(val));
94 | }
95 | if (extraParamMap.containsKey(ElasticConstants.REWRITE)) {
96 | String val = extraParamMap.get(ElasticConstants.REWRITE);
97 | fuzzyQuery.rewrite(val);
98 | }
99 |
100 | if (extraParamMap.containsKey(ElasticConstants.FUZZINESS)) {
101 | String val = extraParamMap.get(ElasticConstants.FUZZINESS).toLowerCase();
102 |
103 | switch (val){
104 | case "0":
105 | case "zero":{
106 | fuzzyQuery.fuzziness(Fuzziness.ZERO);
107 | break;
108 | }
109 | case "1":
110 | case "one":{
111 | fuzzyQuery.fuzziness(Fuzziness.ONE);
112 | break;
113 | }
114 | case "2":
115 | case "two":{
116 | fuzzyQuery.fuzziness(Fuzziness.TWO);
117 | break;
118 | }
119 | default:{
120 | fuzzyQuery.fuzziness(Fuzziness.AUTO);
121 | }
122 | }
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/PrefixQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.cons.ElasticConstants;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.AbstractFieldSpecificMethodQueryParser;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
9 | import org.apache.commons.collections4.MapUtils;
10 | import org.apache.commons.lang3.StringUtils;
11 | import org.elasticsearch.index.query.PrefixQueryBuilder;
12 | import org.elasticsearch.index.query.QueryBuilder;
13 | import org.elasticsearch.index.query.QueryBuilders;
14 |
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | /**
19 | * @author iamazy
20 | */
21 | public class PrefixQueryParser extends AbstractFieldSpecificMethodQueryParser {
22 |
23 | private static List PREFIX_QUERY_METHOD = ImmutableList.of("prefix", "prefix_query", "prefixQuery");
24 |
25 | @Override
26 | public List defineMethodNames() {
27 | return PREFIX_QUERY_METHOD;
28 | }
29 |
30 | @Override
31 | public SQLExpr defineFieldExpr(MethodInvocation invocation) {
32 | return invocation.getParameter(0);
33 | }
34 |
35 | @Override
36 | protected String defineExtraParamString(MethodInvocation invocation) {
37 | int extraParamIdx = 2;
38 |
39 | return (invocation.getParameterCount() == extraParamIdx + 1)
40 | ? invocation.getParameterAsString(extraParamIdx) : StringUtils.EMPTY;
41 | }
42 |
43 | @Override
44 | public void checkMethodInvocation(MethodInvocation invocation) {
45 | if (invocation.getParameterCount() != 2 && invocation.getParameterCount() != 3) {
46 | throw new ElasticSql2DslException(
47 | String.format("[syntax error] There's no %s args method named [%s].",
48 | invocation.getParameterCount(), invocation.getMethodName()));
49 | }
50 |
51 | String text = invocation.getParameterAsString(1);
52 | if (StringUtils.isEmpty(text)) {
53 | throw new ElasticSql2DslException("[syntax error] Prefix search text can not be blank!");
54 | }
55 |
56 | if (invocation.getParameterCount() == 3) {
57 | String extraParamString = defineExtraParamString(invocation);
58 | if (StringUtils.isEmpty(extraParamString)) {
59 | throw new ElasticSql2DslException("[syntax error] The extra param of prefix method can not be blank");
60 | }
61 | }
62 | }
63 |
64 | @Override
65 | protected QueryBuilder buildQuery(MethodInvocation invocation, String fieldName, Map extraParams) {
66 | String text = invocation.getParameterAsString(1);
67 | PrefixQueryBuilder prefixQuery = QueryBuilders.prefixQuery(fieldName, text);
68 |
69 | setExtraMatchQueryParam(prefixQuery, extraParams);
70 | return prefixQuery;
71 | }
72 |
73 | private void setExtraMatchQueryParam(PrefixQueryBuilder prefixQuery, Map extraParamMap) {
74 | if (MapUtils.isEmpty(extraParamMap)) {
75 | return;
76 | }
77 | if (extraParamMap.containsKey(ElasticConstants.BOOST)) {
78 | String val = extraParamMap.get(ElasticConstants.BOOST);
79 | prefixQuery.boost(Float.valueOf(val));
80 | }
81 | if (extraParamMap.containsKey(ElasticConstants.REWRITE)) {
82 | String val = extraParamMap.get(ElasticConstants.REWRITE);
83 | prefixQuery.rewrite(val);
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/RegexpQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import com.google.common.collect.Lists;
6 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
7 | import io.github.iamazy.elasticsearch.dsl.cons.ElasticConstants;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.AbstractFieldSpecificMethodQueryParser;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
10 | import org.apache.commons.collections4.MapUtils;
11 | import org.apache.commons.lang3.StringUtils;
12 | import org.elasticsearch.index.query.QueryBuilder;
13 | import org.elasticsearch.index.query.QueryBuilders;
14 | import org.elasticsearch.index.query.RegexpFlag;
15 | import org.elasticsearch.index.query.RegexpQueryBuilder;
16 |
17 |
18 | import java.util.List;
19 | import java.util.Map;
20 |
21 | public class RegexpQueryParser extends AbstractFieldSpecificMethodQueryParser {
22 |
23 | private static List REGEXP_QUERY_METHOD = ImmutableList.of("regexp", "regexp_query", "regexpQuery");
24 |
25 | RegexpQueryParser() {
26 |
27 | }
28 |
29 | @Override
30 | public List defineMethodNames() {
31 | return REGEXP_QUERY_METHOD;
32 | }
33 |
34 | @Override
35 | public SQLExpr defineFieldExpr(MethodInvocation invocation) {
36 | return invocation.getParameter(0);
37 | }
38 |
39 | @Override
40 | protected String defineExtraParamString(MethodInvocation invocation) {
41 | int extraParamIdx = 2;
42 |
43 | return (invocation.getParameterCount() == extraParamIdx + 1)
44 | ? invocation.getParameterAsString(extraParamIdx) : StringUtils.EMPTY;
45 | }
46 |
47 | @Override
48 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
49 | if (invocation.getParameterCount() != 2 && invocation.getParameterCount() != 3) {
50 | throw new ElasticSql2DslException(
51 | String.format("[syntax error] There's no %s args method named [%s].",
52 | invocation.getParameterCount(), invocation.getMethodName()));
53 | }
54 |
55 | String text = invocation.getParameterAsString(1);
56 | if (StringUtils.isEmpty(text)) {
57 | throw new ElasticSql2DslException("[syntax error] Regexp search text can not be blank!");
58 | }
59 |
60 | if (invocation.getParameterCount() == 3) {
61 | String extraParamString = defineExtraParamString(invocation);
62 | if (StringUtils.isEmpty(extraParamString)) {
63 | throw new ElasticSql2DslException("[syntax error] The extra param of regexp method can not be blank");
64 | }
65 | }
66 | }
67 |
68 | @Override
69 | protected QueryBuilder buildQuery(MethodInvocation invocation, String fieldName, Map extraParams) {
70 | String text = invocation.getParameterAsString(1);
71 | RegexpQueryBuilder regexpQuery = QueryBuilders.regexpQuery(fieldName, text);
72 |
73 | setExtraMatchQueryParam(regexpQuery, extraParams);
74 | return regexpQuery;
75 | }
76 |
77 |
78 | private void setExtraMatchQueryParam(RegexpQueryBuilder regexpQuery, Map extraParamMap) {
79 | if (MapUtils.isEmpty(extraParamMap)) {
80 | return;
81 | }
82 | if (extraParamMap.containsKey(ElasticConstants.BOOST)) {
83 | String val = extraParamMap.get(ElasticConstants.BOOST);
84 | regexpQuery.boost(Float.valueOf(val));
85 | }
86 | if (extraParamMap.containsKey(ElasticConstants.REWRITE)) {
87 | String val = extraParamMap.get(ElasticConstants.REWRITE);
88 | regexpQuery.rewrite(val);
89 | }
90 | if (extraParamMap.containsKey(ElasticConstants.MAX_DETERMINIZED_STATES)) {
91 | String val = extraParamMap.get(ElasticConstants.MAX_DETERMINIZED_STATES);
92 | regexpQuery.maxDeterminizedStates(Integer.valueOf(val));
93 | }
94 | if (extraParamMap.containsKey(ElasticConstants.FLAGS)) {
95 | String[] flags = extraParamMap.get(ElasticConstants.FLAGS).split("\\|");
96 | List flagList = Lists.newLinkedList();
97 | for (String flag : flags) {
98 | flagList.add(RegexpFlag.valueOf(flag.toUpperCase()));
99 | }
100 | regexpQuery.flags(flagList.toArray(new RegexpFlag[0]));
101 | }
102 | if (extraParamMap.containsKey(ElasticConstants.FLAGS_VALUE)) {
103 | String[] flags = extraParamMap.get(ElasticConstants.FLAGS_VALUE).split("\\|");
104 | List flagList = Lists.newLinkedList();
105 | for (String flag : flags) {
106 | flagList.add(RegexpFlag.valueOf(flag.toUpperCase()));
107 | }
108 | regexpQuery.flags(flagList.toArray(new RegexpFlag[0]));
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/TermLevelAtomicQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.sql.model.AtomicQuery;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodQueryParser;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
9 |
10 |
11 | import java.util.List;
12 |
13 | public class TermLevelAtomicQueryParser {
14 |
15 | private final List methodQueryParsers;
16 |
17 | public TermLevelAtomicQueryParser() {
18 | methodQueryParsers = ImmutableList.of(
19 | new PrefixQueryParser(),
20 | new TermQueryParser(),
21 | new TermsQueryParser(),
22 | new WildcardQueryParser(),
23 | new RegexpQueryParser(),
24 | new FuzzyQueryParser()
25 | );
26 | }
27 |
28 | public Boolean isTermLevelAtomQuery(MethodInvocation invocation) {
29 | return methodQueryParsers.stream().anyMatch(methodQueryParser -> methodQueryParser.isMatchMethodInvocation(invocation));
30 | }
31 |
32 | public AtomicQuery parseTermLevelAtomQuery(SQLMethodInvokeExpr methodQueryExpr, String queryAs) {
33 | MethodInvocation methodInvocation = new MethodInvocation(methodQueryExpr, queryAs);
34 | MethodQueryParser matchAtomQueryParser = getQueryParser(methodInvocation);
35 | return matchAtomQueryParser.parseMethodQuery(methodInvocation);
36 | }
37 |
38 | private MethodQueryParser getQueryParser(MethodInvocation methodInvocation) {
39 | for (MethodQueryParser methodQueryParserItem : methodQueryParsers) {
40 | if (methodQueryParserItem.isMatchMethodInvocation(methodInvocation)) {
41 | return methodQueryParserItem;
42 | }
43 | }
44 | throw new ElasticSql2DslException(
45 | String.format("[syntax error] Can not support method query expr[%s] condition",
46 | methodInvocation.getMethodName()));
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/TermQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.cons.ElasticConstants;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.AbstractFieldSpecificMethodQueryParser;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
9 | import org.apache.commons.collections4.MapUtils;
10 | import org.apache.commons.lang3.StringUtils;
11 | import org.elasticsearch.index.query.QueryBuilder;
12 | import org.elasticsearch.index.query.QueryBuilders;
13 | import org.elasticsearch.index.query.TermQueryBuilder;
14 |
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | public class TermQueryParser extends AbstractFieldSpecificMethodQueryParser {
19 |
20 | private static List TERM_QUERY_METHOD = ImmutableList.of("term", "term_query", "termQuery");
21 |
22 | @Override
23 | public List defineMethodNames() {
24 | return TERM_QUERY_METHOD;
25 | }
26 |
27 | @Override
28 | public SQLExpr defineFieldExpr(MethodInvocation invocation) {
29 | return invocation.getParameter(0);
30 | }
31 |
32 | @Override
33 | protected String defineExtraParamString(MethodInvocation invocation) {
34 | int extraParamIdx = 2;
35 |
36 | return (invocation.getParameterCount() == extraParamIdx + 1)
37 | ? invocation.getParameterAsString(extraParamIdx) : StringUtils.EMPTY;
38 | }
39 |
40 | @Override
41 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
42 | if (invocation.getParameterCount() != 2 && invocation.getParameterCount() != 3) {
43 | throw new ElasticSql2DslException(
44 | String.format("[syntax error] There's no %s args method named [%s].",
45 | invocation.getParameterCount(), invocation.getMethodName()));
46 | }
47 |
48 | String text = invocation.getParameterAsString(1);
49 | if (StringUtils.isEmpty(text)) {
50 | throw new ElasticSql2DslException("[syntax error] Term search text can not be blank!");
51 | }
52 |
53 | if (invocation.getParameterCount() == 3) {
54 | String extraParamString = defineExtraParamString(invocation);
55 | if (StringUtils.isEmpty(extraParamString)) {
56 | throw new ElasticSql2DslException("[syntax error] The extra param of term method can not be blank");
57 | }
58 | }
59 | }
60 |
61 | @Override
62 | protected QueryBuilder buildQuery(MethodInvocation invocation, String fieldName, Map extraParams) {
63 | String text = invocation.getParameterAsString(1);
64 |
65 | TermQueryBuilder termQuery = QueryBuilders.termQuery(fieldName, text);
66 | setExtraMatchQueryParam(termQuery, extraParams);
67 |
68 | return termQuery;
69 | }
70 |
71 | private void setExtraMatchQueryParam(TermQueryBuilder termQuery, Map extraParamMap) {
72 | if (MapUtils.isEmpty(extraParamMap)) {
73 | return;
74 | }
75 | if (extraParamMap.containsKey(ElasticConstants.BOOST)) {
76 | String val = extraParamMap.get(ElasticConstants.BOOST);
77 | termQuery.boost(Float.valueOf(val));
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/TermsQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import com.google.common.collect.Lists;
6 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.AbstractFieldSpecificMethodQueryParser;
8 | import io.github.iamazy.elasticsearch.dsl.cons.ElasticConstants;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
10 | import org.apache.commons.collections4.MapUtils;
11 | import org.apache.commons.lang3.StringUtils;
12 | import org.elasticsearch.index.query.QueryBuilder;
13 | import org.elasticsearch.index.query.QueryBuilders;
14 | import org.elasticsearch.index.query.TermsQueryBuilder;
15 |
16 | import java.util.List;
17 | import java.util.Map;
18 |
19 | public class TermsQueryParser extends AbstractFieldSpecificMethodQueryParser {
20 |
21 | private static List TERMS_QUERY_METHOD = ImmutableList.of("terms", "terms_query", "termsQuery");
22 |
23 |
24 | @Override
25 | public List defineMethodNames() {
26 | return TERMS_QUERY_METHOD;
27 | }
28 |
29 | @Override
30 | public SQLExpr defineFieldExpr(MethodInvocation invocation) {
31 | return invocation.getParameter(0);
32 | }
33 |
34 | @Override
35 | protected String defineExtraParamString(MethodInvocation invocation) {
36 | String extraParamString = invocation.getLastParameterAsString();
37 | if (isExtraParamsString(extraParamString)) {
38 | return extraParamString;
39 | }
40 | return StringUtils.EMPTY;
41 | }
42 |
43 | @Override
44 | public void checkMethodInvocation(MethodInvocation invocation) {
45 | if (invocation.getParameterCount() <= 1) {
46 | throw new ElasticSql2DslException(
47 | String.format("[syntax error] There's no %s args method named [%s].",
48 | invocation.getParameterCount(), invocation.getMethodName()));
49 | }
50 |
51 | int paramCount = invocation.getParameterCount();
52 |
53 | for (int idx = 1; idx < paramCount - 1; idx++) {
54 | String text = invocation.getParameterAsString(idx);
55 | if (StringUtils.isEmpty(text)) {
56 | throw new ElasticSql2DslException("[syntax error] Terms text can not be blank!");
57 | }
58 | }
59 | }
60 |
61 | @Override
62 | protected QueryBuilder buildQuery(MethodInvocation invocation, String fieldName, Map extraParams) {
63 | int paramCount = invocation.getParameterCount();
64 |
65 | List termTextList = Lists.newArrayList();
66 | for (int idx = 1; idx < paramCount - 1; idx++) {
67 | String text = invocation.getParameterAsString(idx);
68 | termTextList.add(text);
69 | }
70 |
71 | String lastParamText = invocation.getLastParameterAsString();
72 | if (!isExtraParamsString(lastParamText)) {
73 | termTextList.add(lastParamText);
74 | }
75 |
76 | TermsQueryBuilder termsQuery = QueryBuilders.termsQuery(fieldName, termTextList);
77 | setExtraMatchQueryParam(termsQuery, extraParams);
78 | return termsQuery;
79 | }
80 |
81 | private void setExtraMatchQueryParam(TermsQueryBuilder termsQuery, Map extraParamMap) {
82 | if (MapUtils.isEmpty(extraParamMap)) {
83 | return;
84 | }
85 | if (extraParamMap.containsKey(ElasticConstants.BOOST)) {
86 | String val = extraParamMap.get(ElasticConstants.BOOST);
87 | termsQuery.boost(Float.valueOf(val));
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/query/method/term/WildcardQueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.term;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.google.common.collect.ImmutableList;
5 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
6 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.AbstractFieldSpecificMethodQueryParser;
7 | import io.github.iamazy.elasticsearch.dsl.cons.ElasticConstants;
8 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
9 | import org.apache.commons.collections4.MapUtils;
10 | import org.apache.commons.lang3.StringUtils;
11 | import org.elasticsearch.index.query.QueryBuilder;
12 | import org.elasticsearch.index.query.QueryBuilders;
13 | import org.elasticsearch.index.query.WildcardQueryBuilder;
14 |
15 |
16 | import java.util.List;
17 | import java.util.Map;
18 |
19 | public class WildcardQueryParser extends AbstractFieldSpecificMethodQueryParser {
20 |
21 | private static List WILDCARD_QUERY_METHOD = ImmutableList.of("wildcard", "wildcard_query", "wildcardQuery");
22 |
23 | @Override
24 | public List defineMethodNames() {
25 | return WILDCARD_QUERY_METHOD;
26 | }
27 |
28 | @Override
29 | protected String defineExtraParamString(MethodInvocation invocation) {
30 | int extraParamIdx = 2;
31 |
32 | return (invocation.getParameterCount() == extraParamIdx + 1)
33 | ? invocation.getParameterAsString(extraParamIdx) : StringUtils.EMPTY;
34 | }
35 |
36 | @Override
37 | public SQLExpr defineFieldExpr(MethodInvocation invocation) {
38 | return invocation.getParameter(0);
39 | }
40 |
41 | @Override
42 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
43 | if (invocation.getParameterCount() != 2 && invocation.getParameterCount() != 3) {
44 | throw new ElasticSql2DslException(
45 | String.format("[syntax error] There's no %s args method named [%s].",
46 | invocation.getParameterCount(), invocation.getMethodName()));
47 | }
48 |
49 | String text = invocation.getParameterAsString(1);
50 | if (StringUtils.isEmpty(text)) {
51 | throw new ElasticSql2DslException("[syntax error] Wildcard search text can not be blank!");
52 | }
53 |
54 | if (invocation.getParameterCount() == 3) {
55 | String extraParamString = defineExtraParamString(invocation);
56 | if (StringUtils.isEmpty(extraParamString)) {
57 | throw new ElasticSql2DslException("[syntax error] The extra param of wildcard method can not be blank");
58 | }
59 | }
60 | }
61 |
62 | @Override
63 | protected QueryBuilder buildQuery(MethodInvocation invocation, String fieldName, Map extraParams) {
64 | String text = invocation.getParameterAsString(1);
65 | WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery(fieldName, text);
66 |
67 | setExtraMatchQueryParam(wildcardQuery, extraParams);
68 | return wildcardQuery;
69 | }
70 |
71 | private void setExtraMatchQueryParam(WildcardQueryBuilder wildcardQuery, Map extraParamMap) {
72 | if (MapUtils.isEmpty(extraParamMap)) {
73 | return;
74 | }
75 | if (extraParamMap.containsKey(ElasticConstants.BOOST)) {
76 | String val = extraParamMap.get(ElasticConstants.BOOST);
77 | wildcardQuery.boost(Float.valueOf(val));
78 | }
79 | if (extraParamMap.containsKey(ElasticConstants.REWRITE)) {
80 | String val = extraParamMap.get(ElasticConstants.REWRITE);
81 | wildcardQuery.rewrite(val);
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryFromParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
5 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
6 | import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
7 | import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
8 | import com.google.common.collect.Lists;
9 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
10 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
11 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
12 |
13 |
14 | public class QueryFromParser implements QueryParser {
15 |
16 | @Override
17 | public void parse(ElasticDslContext dslContext) {
18 | SQLExprTableSource tableSource;
19 | if (dslContext.getSqlObject() instanceof SQLDeleteStatement) {
20 | SQLDeleteStatement sqlDeleteStatement = (SQLDeleteStatement) dslContext.getSqlObject();
21 | tableSource = sqlDeleteStatement.getExprTableSource();
22 | extractFrom(tableSource,dslContext);
23 | }
24 |
25 | if (dslContext.getSqlObject() instanceof SQLQueryExpr) {
26 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr) dslContext.getSqlObject()).getSubQuery().getQuery();
27 | if (queryBlock.getFrom() instanceof SQLExprTableSource) {
28 | tableSource = (SQLExprTableSource) queryBlock.getFrom();
29 | extractFrom(tableSource,dslContext);
30 | }
31 |
32 | }
33 | }
34 |
35 |
36 | private void extractFrom(SQLExprTableSource tableSource,ElasticDslContext dslContext){
37 | dslContext.getParseResult().setQueryAs(tableSource.getAlias());
38 |
39 | if (tableSource.getExpr() instanceof SQLIdentifierExpr) {
40 | String index = ((SQLIdentifierExpr) tableSource.getExpr()).getName();
41 | dslContext.getParseResult().setIndices(Lists.newArrayList(index));
42 | return;
43 | }
44 |
45 | if (tableSource.getExpr() instanceof SQLPropertyExpr) {
46 | SQLPropertyExpr idxExpr = (SQLPropertyExpr) tableSource.getExpr();
47 |
48 | if (!(idxExpr.getOwner() instanceof SQLIdentifierExpr)) {
49 | throw new ElasticSql2DslException("[syntax error] From table should like [index].[type]");
50 | }
51 |
52 | String index = ((SQLIdentifierExpr) idxExpr.getOwner()).getName();
53 | dslContext.getParseResult().setIndices(Lists.newArrayList(index));
54 | dslContext.getParseResult().setType(idxExpr.getName());
55 | return;
56 | }
57 |
58 | throw new ElasticSql2DslException("[syntax error] From table should like [index].[type]");
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryLimitSizeParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr;
5 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
6 | import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
7 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
8 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
9 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlArgConverter;
10 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
11 |
12 |
13 | public class QueryLimitSizeParser implements QueryParser {
14 |
15 |
16 |
17 | public QueryLimitSizeParser() { }
18 |
19 | @Override
20 | public void parse(ElasticDslContext dslContext) {
21 |
22 | if (dslContext.getSqlObject() instanceof SQLQueryExpr) {
23 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr) dslContext.getSqlObject()).getSubQuery().getQuery();
24 | if (queryBlock.getLimit0() != null) {
25 | Integer from = parseLimitInteger(queryBlock.getLimit0().getOffset());
26 | dslContext.getParseResult().setFrom(from);
27 |
28 | Integer size = parseLimitInteger(queryBlock.getLimit0().getRowCount());
29 | dslContext.getParseResult().setSize(size);
30 | } else {
31 | dslContext.getParseResult().setFrom(0);
32 | dslContext.getParseResult().setSize(15);
33 | }
34 | }
35 | }
36 |
37 | private Integer parseLimitInteger(SQLExpr limitInt) {
38 | if (limitInt instanceof SQLIntegerExpr) {
39 | return ((SQLIntegerExpr) limitInt).getNumber().intValue();
40 | } else if (limitInt instanceof SQLVariantRefExpr) {
41 | SQLVariantRefExpr varLimitExpr = (SQLVariantRefExpr) limitInt;
42 | Object targetVal = ElasticSqlArgConverter.convertSqlArg(varLimitExpr);
43 | if (!(targetVal instanceof Integer)) {
44 | throw new ElasticSql2DslException("[syntax error] Sql limit expr should be a non-negative number");
45 | }
46 | return Integer.valueOf(targetVal.toString());
47 | } else {
48 | throw new ElasticSql2DslException("[syntax error] Sql limit expr should be a non-negative number");
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryMatchConditionParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 |
4 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
5 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
6 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
7 | import org.elasticsearch.index.query.BoolQueryBuilder;
8 |
9 | /**
10 | * @author iamazy
11 | */
12 | public class QueryMatchConditionParser extends BoolExpressionParser implements QueryParser{
13 |
14 | @Override
15 | public void parse(ElasticDslContext dslContext) {
16 |
17 | if(dslContext.getSqlObject() instanceof SQLQueryExpr) {
18 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr) dslContext.getSqlObject()).getSubQuery().getQuery();
19 | if (queryBlock.getMatchQuery() != null) {
20 | String queryAs = dslContext.getParseResult().getQueryAs();
21 | BoolQueryBuilder matchQuery = parseBoolQueryExpr(queryBlock.getMatchQuery(), queryAs);
22 | dslContext.getParseResult().setMatchCondition(matchQuery);
23 | dslContext.getParseResult().getHighlighter().addAll(this.getHighlighter());
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryOrderConditionParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.SQLOrderBy;
4 | import com.alibaba.druid.sql.ast.SQLOrderingSpecification;
5 | import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
6 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
7 | import com.alibaba.druid.sql.ast.statement.SQLSelectOrderByItem;
8 | import com.google.common.collect.ImmutableList;
9 | import com.google.common.collect.Lists;
10 |
11 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
12 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
13 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
14 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort.*;
15 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
16 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlQueryField;
17 | import org.apache.commons.collections4.CollectionUtils;
18 | import org.elasticsearch.search.sort.SortBuilder;
19 | import org.elasticsearch.search.sort.SortBuilders;
20 | import org.elasticsearch.search.sort.SortOrder;
21 |
22 |
23 | import java.util.List;
24 |
25 | public class QueryOrderConditionParser implements QueryParser {
26 |
27 |
28 | private List methodSortParsers;
29 |
30 | public QueryOrderConditionParser() {
31 |
32 | methodSortParsers = ImmutableList.of(
33 | new NvlMethodSortParser(),
34 | new ScriptMethodSortParser(),
35 | new NestedSortMethodParser()
36 | );
37 | }
38 |
39 | @Override
40 | public void parse(ElasticDslContext dslContext) {
41 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr)dslContext.getSqlObject()).getSubQuery().getQuery();
42 | SQLOrderBy sqlOrderBy = queryBlock.getOrderBy();
43 | if (sqlOrderBy != null && CollectionUtils.isNotEmpty(sqlOrderBy.getItems())) {
44 | List orderByList = Lists.newLinkedList();
45 |
46 | String queryAs = dslContext.getParseResult().getQueryAs();
47 |
48 | for (SQLSelectOrderByItem orderByItem : sqlOrderBy.getItems()) {
49 | SortBuilder orderBy = parseOrderCondition(orderByItem, queryAs);
50 | if (orderBy != null) {
51 | orderByList.add(orderBy);
52 | }
53 | }
54 | dslContext.getParseResult().setOrderBy(orderByList);
55 | }
56 | }
57 |
58 | private SortBuilder parseOrderCondition(SQLSelectOrderByItem orderByItem, String queryAs) {
59 |
60 | SortOrder order = orderByItem.getType() == SQLOrderingSpecification.ASC ? SortOrder.ASC : SortOrder.DESC;
61 |
62 | if (ParseSortBuilderHelper.isFieldExpr(orderByItem.getExpr())) {
63 | QueryFieldParser fieldParser = new QueryFieldParser();
64 | ElasticSqlQueryField sortField = fieldParser.parseConditionQueryField(orderByItem.getExpr(), queryAs);
65 | return ParseSortBuilderHelper.parseBasedOnFieldSortBuilder(sortField, queryFieldName -> SortBuilders.fieldSort(queryFieldName).order(order));
66 | }
67 |
68 | if (ParseSortBuilderHelper.isMethodInvokeExpr(orderByItem.getExpr())) {
69 | MethodInvocation sortMethodInvocation = new MethodInvocation((SQLMethodInvokeExpr) orderByItem.getExpr(), queryAs);
70 | for (MethodSortParser methodSortParser : methodSortParsers) {
71 | if (methodSortParser.isMatchMethodInvocation(sortMethodInvocation)) {
72 | return methodSortParser.parseMethodSortBuilder(sortMethodInvocation, order);
73 | }
74 | }
75 | }
76 |
77 | throw new ElasticSql2DslException("[syntax error] can not support sort type: " + orderByItem.getExpr().getClass());
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 |
4 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
5 |
6 | @FunctionalInterface
7 | public interface QueryParser {
8 | void parse(ElasticDslContext dslContext);
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryRoutingValParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
5 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
6 | import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
7 | import com.google.common.collect.Lists;
8 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
9 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
10 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlArgConverter;
11 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
12 | import org.apache.commons.collections4.CollectionUtils;
13 |
14 |
15 | import java.util.List;
16 |
17 | public class QueryRoutingValParser implements QueryParser {
18 |
19 |
20 | @Override
21 | public void parse(ElasticDslContext dslContext) {
22 |
23 | if(dslContext.getSqlObject() instanceof SQLQueryExpr) {
24 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr) dslContext.getSqlObject()).getSubQuery().getQuery();
25 | if (queryBlock.getRouting() != null && CollectionUtils.isNotEmpty(queryBlock.getRouting().getRoutingValues())) {
26 | List routingStringValues = Lists.newLinkedList();
27 | for (SQLExpr routingVal : queryBlock.getRouting().getRoutingValues()) {
28 | if (routingVal instanceof SQLCharExpr) {
29 | routingStringValues.add(((SQLCharExpr) routingVal).getText());
30 | } else if (routingVal instanceof SQLVariantRefExpr) {
31 | Object targetVal = ElasticSqlArgConverter.convertSqlArg(routingVal);
32 | routingStringValues.add(targetVal.toString());
33 | } else {
34 | throw new ElasticSql2DslException("[syntax error] Index routing val must be a string");
35 | }
36 | }
37 | dslContext.getParseResult().setRoutingBy(routingStringValues);
38 | }
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryScrollParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
5 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
6 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
7 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
8 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
9 |
10 |
11 | /**
12 | * @author iamazy
13 | * @date 2019/3/25
14 | * @descrition
15 | **/
16 | public class QueryScrollParser implements QueryParser {
17 |
18 | public QueryScrollParser() { }
19 |
20 | @Override
21 | public void parse(ElasticDslContext dslContext) {
22 |
23 | if (dslContext.getSqlObject() instanceof SQLQueryExpr) {
24 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr) dslContext.getSqlObject()).getSubQuery().getQuery();
25 | if (queryBlock.getScroll() != null) {
26 | String expire = parseScroll(queryBlock.getScroll().getExpire());
27 | dslContext.getParseResult().setScrollExpire(expire);
28 | if(queryBlock.getScroll().getScrollId()!=null) {
29 | String scrollId = parseScroll(queryBlock.getScroll().getScrollId());
30 | dslContext.getParseResult().setScrollId(scrollId);
31 | }
32 | }
33 | }
34 | }
35 |
36 | private String parseScroll(SQLExpr sqlExpr) {
37 | if (sqlExpr instanceof SQLCharExpr) {
38 | return ((SQLCharExpr) sqlExpr).getText();
39 | } else {
40 | throw new ElasticSql2DslException("[syntax error] Sql scroll expr should be a string expr");
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QuerySelectFieldListParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr;
5 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
6 | import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
7 | import com.google.common.collect.Lists;
8 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
9 | import io.github.iamazy.elasticsearch.dsl.sql.enums.QueryFieldType;
10 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
11 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlMethodInvokeHelper;
12 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
13 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlQueryField;
14 | import org.apache.commons.collections4.CollectionUtils;
15 | import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
16 | import org.elasticsearch.search.aggregations.AggregationBuilder;
17 | import org.elasticsearch.search.aggregations.AggregationBuilders;
18 |
19 | import java.util.List;
20 |
21 | public class QuerySelectFieldListParser implements QueryParser {
22 |
23 |
24 | @Override
25 | public void parse(ElasticDslContext dslContext) {
26 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr)dslContext.getSqlObject()).getSubQuery().getQuery();
27 |
28 | List selectFields = Lists.newLinkedList();
29 | QueryFieldParser queryFieldParser = new QueryFieldParser();
30 | String queryAs = dslContext.getParseResult().getQueryAs();
31 |
32 | List aggregations = Lists.newLinkedList();
33 | for (SQLSelectItem selectField : queryBlock.getSelectList()) {
34 |
35 | // agg method
36 | if (selectField.getExpr() instanceof SQLAggregateExpr) {
37 |
38 | SQLAggregateExpr aggExpr = (SQLAggregateExpr) selectField.getExpr();
39 | SQLExpr aggFieldExpr = aggExpr.getArguments().get(0);
40 |
41 | ElasticSqlQueryField aggField = queryFieldParser.parseConditionQueryField(aggFieldExpr, queryAs);
42 | AbstractAggregationBuilder statsAgg = parseStatsAggregation(aggExpr, aggField.getQueryFieldFullName());
43 |
44 | aggregations.add(statsAgg);
45 | continue;
46 | }
47 |
48 | // select field
49 | ElasticSqlQueryField sqlSelectField = queryFieldParser.parseSelectQueryField(selectField.getExpr(), queryAs);
50 |
51 | if (sqlSelectField.getQueryFieldType() == QueryFieldType.SqlSelectField) {
52 | selectFields.add(sqlSelectField.getQueryFieldFullName());
53 | }
54 | }
55 |
56 | if (CollectionUtils.isNotEmpty(aggregations)) {
57 | List groupByList = dslContext.getParseResult().getGroupBy();
58 |
59 | if (CollectionUtils.isNotEmpty(groupByList)) {
60 | AggregationBuilder lastLevelAggItem = groupByList.get(groupByList.size() - 1);
61 | for (AggregationBuilder aggItem : aggregations) {
62 | lastLevelAggItem.subAggregation(aggItem);
63 | }
64 | }
65 | else {
66 | dslContext.getParseResult().setGroupBy(aggregations);
67 | }
68 | }
69 |
70 | dslContext.getParseResult().setQueryFieldList(selectFields);
71 | }
72 |
73 | private AbstractAggregationBuilder parseStatsAggregation(SQLAggregateExpr aggExpr, String fieldName) {
74 | ElasticSqlMethodInvokeHelper.checkStatAggMethod(aggExpr);
75 |
76 | String methodName = aggExpr.getMethodName();
77 | if (ElasticSqlMethodInvokeHelper.AGG_MIN_METHOD.equalsIgnoreCase(methodName)) {
78 | return AggregationBuilders.min(String.format("%s_%s", ElasticSqlMethodInvokeHelper.AGG_MIN_METHOD, fieldName)).field(fieldName);
79 | }
80 |
81 | if (ElasticSqlMethodInvokeHelper.AGG_MAX_METHOD.equalsIgnoreCase(methodName)) {
82 | return AggregationBuilders.max(String.format("%s_%s", ElasticSqlMethodInvokeHelper.AGG_MAX_METHOD, fieldName)).field(fieldName);
83 | }
84 |
85 | if (ElasticSqlMethodInvokeHelper.AGG_AVG_METHOD.equalsIgnoreCase(methodName)) {
86 | return AggregationBuilders.avg(String.format("%s_%s", ElasticSqlMethodInvokeHelper.AGG_AVG_METHOD, fieldName)).field(fieldName);
87 | }
88 |
89 | if (ElasticSqlMethodInvokeHelper.AGG_SUM_METHOD.equalsIgnoreCase(methodName)) {
90 | return AggregationBuilders.sum(String.format("%s_%s", ElasticSqlMethodInvokeHelper.AGG_SUM_METHOD, fieldName)).field(fieldName);
91 | }
92 | throw new ElasticSql2DslException(String.format("[syntax error] UnSupport agg method call[%s]", methodName));
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/QueryWhereConditionParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
5 | import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
6 | import io.github.iamazy.elasticsearch.dsl.sql.druid.ElasticSqlSelectQueryBlock;
7 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
8 | import org.elasticsearch.index.query.BoolQueryBuilder;
9 |
10 |
11 | public class QueryWhereConditionParser extends BoolExpressionParser implements QueryParser{
12 |
13 |
14 | @Override
15 | public void parse(ElasticDslContext dslContext) {
16 |
17 | if(dslContext.getSqlObject() instanceof SQLDeleteStatement){
18 | SQLDeleteStatement sqlDeleteStatement = (SQLDeleteStatement) dslContext.getSqlObject();
19 | String queryAs=dslContext.getParseResult().getQueryAs();
20 | SQLExpr sqlExpr=sqlDeleteStatement.getWhere();
21 | BoolQueryBuilder matchQuery=parseBoolQueryExpr(sqlExpr,queryAs);
22 | dslContext.getParseResult().setMatchCondition(matchQuery);
23 | }
24 | if(dslContext.getSqlObject() instanceof SQLQueryExpr) {
25 | ElasticSqlSelectQueryBlock queryBlock = (ElasticSqlSelectQueryBlock) ((SQLQueryExpr) dslContext.getSqlObject()).getSubQuery().getQuery();
26 |
27 | if (queryBlock.getWhere() != null) {
28 | String queryAs = dslContext.getParseResult().getQueryAs();
29 | BoolQueryBuilder whereQuery = parseBoolQueryExpr(queryBlock.getWhere(), queryAs);
30 | dslContext.getParseResult().setWhereCondition(whereQuery);
31 | dslContext.getParseResult().getHighlighter().addAll(this.getHighlighter());
32 | }
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/AbstractMethodSortParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 |
4 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
5 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
6 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.expr.AbstractParameterizedMethodExpression;
7 | import io.github.iamazy.elasticsearch.dsl.sql.helper.ElasticSqlMethodInvokeHelper;
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.elasticsearch.search.sort.SortBuilder;
10 | import org.elasticsearch.search.sort.SortOrder;
11 |
12 | import java.util.Map;
13 |
14 | public abstract class AbstractMethodSortParser extends AbstractParameterizedMethodExpression implements MethodSortParser {
15 |
16 | protected abstract SortBuilder parseMethodSortBuilder(
17 | MethodInvocation invocation, SortOrder order, Map extraParamMap) throws ElasticSql2DslException;
18 |
19 | @Override
20 | protected String defineExtraParamString(MethodInvocation invocation) {
21 | return StringUtils.EMPTY;
22 | }
23 |
24 | @Override
25 | public void checkMethodInvocation(MethodInvocation invocation) throws ElasticSql2DslException {
26 |
27 | }
28 |
29 | @Override
30 | public boolean isMatchMethodInvocation(MethodInvocation invocation) {
31 | return ElasticSqlMethodInvokeHelper.isMethodOf(defineMethodNames(), invocation.getMethodName());
32 | }
33 |
34 | @Override
35 | public SortBuilder parseMethodSortBuilder(MethodInvocation invocation, SortOrder order) throws ElasticSql2DslException {
36 | if (!isMatchMethodInvocation(invocation)) {
37 | throw new ElasticSql2DslException(
38 | String.format("[syntax error] Expected method name is one of [%s],but get [%s]",
39 | defineMethodNames(), invocation.getMethodName()));
40 | }
41 | checkMethodInvocation(invocation);
42 |
43 | Map extraParamMap = generateRawTypeParameterMap(invocation);
44 | return parseMethodSortBuilder(invocation, order, extraParamMap);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/ConditionSortBuilder.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 | import org.elasticsearch.search.sort.FieldSortBuilder;
4 |
5 | public interface ConditionSortBuilder {
6 | FieldSortBuilder buildSort(String idfName);
7 | }
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/MethodSortParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
5 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.expr.MethodExpression;
6 | import org.elasticsearch.search.sort.SortBuilder;
7 | import org.elasticsearch.search.sort.SortOrder;
8 |
9 |
10 | public interface MethodSortParser extends MethodExpression {
11 | SortBuilder parseMethodSortBuilder(MethodInvocation invocation, SortOrder order) throws ElasticSql2DslException;
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/NestedSortMethodParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
5 | import com.google.common.collect.ImmutableList;
6 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
8 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlQueryField;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.BoolExpressionParser;
10 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.QueryFieldParser;
11 | import org.elasticsearch.index.query.BoolQueryBuilder;
12 | import org.elasticsearch.search.sort.*;
13 |
14 |
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | /**
19 | * nested sort(nestedField, sortMode, missingValue, defaultValue, filterExpression)
20 | *
21 | * order by nested_sort($repaymentRecords.principal, 'min', 0, repaymentRecords.status='DONE') asc
22 | */
23 | public class NestedSortMethodParser extends AbstractMethodSortParser {
24 |
25 | public static final List NESTED_SORT_METHOD = ImmutableList.of("nested_sort", "nestedSort");
26 |
27 | @Override
28 | public List defineMethodNames() {
29 | return NESTED_SORT_METHOD;
30 | }
31 |
32 | @Override
33 | public void checkMethodInvocation(MethodInvocation nestedSortMethodInvocation) throws ElasticSql2DslException {
34 | if (!isMatchMethodInvocation(nestedSortMethodInvocation)) {
35 | throw new ElasticSql2DslException(
36 | String.format("[syntax error] No suck sort method[%s]", nestedSortMethodInvocation.getMethodName()));
37 | }
38 |
39 | if (nestedSortMethodInvocation.getParameterCount() > 4) {
40 | throw new ElasticSql2DslException(
41 | String.format("[syntax error] There is no %s args method named nested_sort",
42 | nestedSortMethodInvocation.getParameterCount()));
43 | }
44 |
45 | SQLExpr sortModArg = nestedSortMethodInvocation.getParameter(1);
46 | if (!(sortModArg instanceof SQLCharExpr)) {
47 | throw new ElasticSql2DslException("[syntax error] The second arg of nested_sort method should be string");
48 | }
49 |
50 | String sortModeText = ((SQLCharExpr) sortModArg).getText();
51 | SortMode.fromString(sortModeText);
52 | }
53 |
54 | @Override
55 | protected SortBuilder parseMethodSortBuilder(MethodInvocation invocation, SortOrder order, Map extraParamMap) throws ElasticSql2DslException {
56 | String sortMode = invocation.getParameterAsString(1);
57 | Object defaultSortVal = invocation.getParameterAsObject(2);
58 |
59 | boolean hasFilterExpr = invocation.getParameterCount() == 4;
60 |
61 | QueryFieldParser queryFieldParser = new QueryFieldParser();
62 | ElasticSqlQueryField sortField = queryFieldParser.parseConditionQueryField(invocation.getParameter(0), invocation.getQueryAs());
63 |
64 | return ParseSortBuilderHelper.parseBasedOnFieldSortBuilder(sortField, nestedFieldName -> {
65 | BoolQueryBuilder filter = null;
66 | if (hasFilterExpr) {
67 | SQLExpr filterExpr = invocation.getParameter(3);
68 |
69 | BoolExpressionParser boolExpressionParser = new BoolExpressionParser();
70 |
71 | String queryAs = invocation.getQueryAs();
72 |
73 | filter = boolExpressionParser.parseBoolQueryExpr(filterExpr, queryAs);
74 | }
75 |
76 | if(sortField.getNestedDocContextPath().size()==1) {
77 | return SortBuilders.fieldSort(nestedFieldName)
78 | .missing(defaultSortVal).sortMode(SortMode.fromString(sortMode))
79 | .setNestedSort(new NestedSortBuilder(sortField.getNestedDocContextPath().get(0)).setFilter(hasFilterExpr ? filter : null))
80 | .order(order);
81 | }else if(sortField.getNestedDocContextPath().size()==2){
82 | return SortBuilders.fieldSort(nestedFieldName)
83 | .missing(defaultSortVal).sortMode(SortMode.fromString(sortMode))
84 | .setNestedSort(new NestedSortBuilder(sortField.getNestedDocContextPath().get(0)).setNestedSort(new NestedSortBuilder(sortField.getNestedDocContextPath().get(1)).setFilter(hasFilterExpr ? filter : null)))
85 | .order(order);
86 | }else{
87 | throw new ElasticSql2DslException("[syntax error] can not support sql for 3 more nested sort aggregation");
88 | }
89 | });
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/NvlMethodSortParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.*;
5 | import com.google.common.collect.ImmutableList;
6 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
7 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
8 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlQueryField;
9 | import io.github.iamazy.elasticsearch.dsl.sql.parser.sql.QueryFieldParser;
10 | import org.elasticsearch.search.sort.*;
11 |
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | /**
16 | * nvl(rootDocField, defaultValue)
17 | *
18 | * order by nvl(price, 0) asc
19 | *
20 | * @author chennan
21 | */
22 | public class NvlMethodSortParser extends AbstractMethodSortParser {
23 |
24 | public static final List NVL_METHOD = ImmutableList.of("nvl", "is_null", "isnull");
25 |
26 | @Override
27 | public List defineMethodNames() {
28 | return NVL_METHOD;
29 | }
30 |
31 | @Override
32 | public void checkMethodInvocation(MethodInvocation nvlMethodInvocation) throws ElasticSql2DslException {
33 | if (!isMatchMethodInvocation(nvlMethodInvocation)) {
34 | throw new ElasticSql2DslException("[syntax error] Sql sort condition only support nvl method invoke");
35 | }
36 |
37 | int methodParameterCount = nvlMethodInvocation.getParameterCount();
38 | if (methodParameterCount == 0 || methodParameterCount >= 3) {
39 | throw new ElasticSql2DslException(String.format("[syntax error] There is no %s args method named nvl", methodParameterCount));
40 | }
41 |
42 | SQLExpr fieldArg = nvlMethodInvocation.getParameter(0);
43 | SQLExpr valueArg = nvlMethodInvocation.getParameter(1);
44 |
45 | if (!(fieldArg instanceof SQLPropertyExpr) && !(fieldArg instanceof SQLIdentifierExpr)) {
46 | throw new ElasticSql2DslException("[syntax error] The first arg of nvl method should be field param name");
47 | }
48 |
49 | if (!(valueArg instanceof SQLCharExpr) && !(valueArg instanceof SQLIntegerExpr) && !(valueArg instanceof SQLNumberExpr)) {
50 | throw new ElasticSql2DslException("[syntax error] The second arg of nvl method should be number or string");
51 | }
52 | }
53 |
54 | @Override
55 | protected SortBuilder parseMethodSortBuilder(
56 | MethodInvocation sortMethodInvocation, SortOrder order, Map extraParamMap) throws ElasticSql2DslException {
57 |
58 | String queryAs = sortMethodInvocation.getQueryAs();
59 | SQLExpr fieldExpr = sortMethodInvocation.getParameter(0);
60 | Object valueArg = sortMethodInvocation.getParameterAsObject(1);
61 |
62 | QueryFieldParser queryFieldParser = new QueryFieldParser();
63 | ElasticSqlQueryField sortField = queryFieldParser.parseConditionQueryField(fieldExpr, queryAs);
64 |
65 | return ParseSortBuilderHelper.parseBasedOnFieldSortBuilder(sortField, idfName -> {
66 | FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort(idfName).order(order).missing(valueArg);
67 |
68 | if (sortMethodInvocation.getParameterCount() == 3) {
69 | String sortModeText = sortMethodInvocation.getParameterAsString(2);
70 | fieldSortBuilder.sortMode(SortMode.fromString(sortModeText));
71 | }
72 | return fieldSortBuilder;
73 | });
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/ParseSortBuilderHelper.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 | import com.alibaba.druid.sql.ast.SQLExpr;
4 | import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
5 | import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
6 | import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
7 | import io.github.iamazy.elasticsearch.dsl.sql.enums.QueryFieldType;
8 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
9 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlQueryField;
10 | import org.elasticsearch.search.sort.FieldSortBuilder;
11 | import org.elasticsearch.search.sort.NestedSortBuilder;
12 | import org.elasticsearch.search.sort.SortBuilder;
13 |
14 |
15 | public class ParseSortBuilderHelper {
16 |
17 | public static boolean isFieldExpr(SQLExpr expr) {
18 | return expr instanceof SQLPropertyExpr || expr instanceof SQLIdentifierExpr;
19 | }
20 |
21 | public static boolean isMethodInvokeExpr(SQLExpr expr) {
22 | return expr instanceof SQLMethodInvokeExpr;
23 | }
24 |
25 | public static SortBuilder parseBasedOnFieldSortBuilder(ElasticSqlQueryField sortField, ConditionSortBuilder sortBuilder) {
26 | SortBuilder rtnSortBuilder = null;
27 | if (sortField.getQueryFieldType() == QueryFieldType.RootDocField || sortField.getQueryFieldType() == QueryFieldType.InnerDocField) {
28 | rtnSortBuilder = sortBuilder.buildSort(sortField.getQueryFieldFullName());
29 | }
30 |
31 | if (sortField.getQueryFieldType() == QueryFieldType.NestedDocField) {
32 | FieldSortBuilder originalSort = sortBuilder.buildSort(sortField.getQueryFieldFullName());
33 | if(sortField.getNestedDocContextPath().size()==1) {
34 | originalSort.setNestedSort(new NestedSortBuilder(sortField.getNestedDocContextPath().get(0)));
35 | }else if(sortField.getNestedDocContextPath().size()==2){
36 | originalSort.setNestedSort(new NestedSortBuilder(sortField.getNestedDocContextPath().get(0)).setNestedSort(new NestedSortBuilder(sortField.getNestedDocContextPath().get(1))));
37 | }
38 | rtnSortBuilder = originalSort;
39 | }
40 |
41 | if (rtnSortBuilder == null) {
42 | throw new ElasticSql2DslException(String.format("[syntax error] sort condition field can not support type[%s]", sortField.getQueryFieldType()));
43 | }
44 |
45 | return rtnSortBuilder;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/sql/parser/sql/sort/ScriptMethodSortParser.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql.parser.sql.sort;
2 |
3 | import com.google.common.collect.ImmutableList;
4 | import io.github.iamazy.elasticsearch.dsl.sql.exception.ElasticSql2DslException;
5 | import io.github.iamazy.elasticsearch.dsl.sql.parser.query.method.MethodInvocation;
6 | import org.apache.commons.collections4.MapUtils;
7 | import org.apache.commons.lang3.StringUtils;
8 | import org.elasticsearch.script.Script;
9 | import org.elasticsearch.search.sort.ScriptSortBuilder;
10 | import org.elasticsearch.search.sort.SortBuilder;
11 | import org.elasticsearch.search.sort.SortBuilders;
12 | import org.elasticsearch.search.sort.SortOrder;
13 |
14 |
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | public class ScriptMethodSortParser extends AbstractMethodSortParser {
19 |
20 | public static final List SCRIPT_SORT_METHOD = ImmutableList.of("script_sort", "scriptSort");
21 |
22 | @Override
23 | public List defineMethodNames() {
24 | return SCRIPT_SORT_METHOD;
25 | }
26 |
27 | @Override
28 | protected String defineExtraParamString(MethodInvocation invocation) {
29 | if (invocation.getParameterCount() == 3) {
30 | return invocation.getParameterAsString(2);
31 | }
32 | return StringUtils.EMPTY;
33 | }
34 |
35 | @Override
36 | public void checkMethodInvocation(MethodInvocation nvlMethodInvocation) throws ElasticSql2DslException {
37 | if (!isMatchMethodInvocation(nvlMethodInvocation)) {
38 | throw new ElasticSql2DslException("[syntax error] Sql sort condition only support script_query method invoke");
39 | }
40 |
41 | int methodParameterCount = nvlMethodInvocation.getParameterCount();
42 | if (methodParameterCount != 2 && methodParameterCount != 3) {
43 | throw new ElasticSql2DslException(String.format("[syntax error] There is no %s args method named script_sort", methodParameterCount));
44 | }
45 | }
46 |
47 | @Override
48 | protected SortBuilder parseMethodSortBuilder(
49 | MethodInvocation scriptSortMethodInvocation, SortOrder order, Map extraParamMap) throws ElasticSql2DslException {
50 |
51 | String strScript = scriptSortMethodInvocation.getParameterAsString(0);
52 | String type = scriptSortMethodInvocation.getParameterAsString(1);
53 | ScriptSortBuilder.ScriptSortType scriptSortType = ScriptSortBuilder.ScriptSortType.fromString(type);
54 |
55 | if (MapUtils.isNotEmpty(extraParamMap)) {
56 | Map scriptParamMap = generateRawTypeParameterMap(scriptSortMethodInvocation);
57 | Script scriptObject = new Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG, strScript, scriptParamMap);
58 | return SortBuilders.scriptSort(scriptObject, scriptSortType).order(order);
59 | }
60 |
61 | return SortBuilders.scriptSort(new Script(strScript), scriptSortType).order(order);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/io/github/iamazy/elasticsearch/dsl/utils/FlatMapUtils.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.utils;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.cons.CoreConstants;
4 | import org.apache.commons.lang3.StringUtils;
5 |
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | /**
10 | * @author iamazy
11 | * @date 2019/4/11
12 | * @descrition
13 | **/
14 | @SuppressWarnings("unchecked")
15 | public class FlatMapUtils {
16 |
17 | public static Map flat(Map map, String parentKey) {
18 | String parent = parentKey;
19 | Map dataInfo = new HashMap<>(0);
20 | for (Map.Entry entry : map.entrySet()) {
21 | if (!(entry.getValue() instanceof Map)) {
22 | if (StringUtils.isNotBlank(parent)) {
23 | dataInfo.put(parent + CoreConstants.DOT + entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : StringUtils.EMPTY);
24 | } else {
25 | dataInfo.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : StringUtils.EMPTY);
26 | }
27 | } else {
28 | Map childMap = (Map) entry.getValue();
29 | if (StringUtils.isNotBlank(parent)) {
30 | parent = parent + CoreConstants.DOT + entry.getKey();
31 | } else {
32 | parent = entry.getKey();
33 | }
34 | dataInfo.putAll(flat(childMap, parent));
35 | if(parent.contains(CoreConstants.DOT)) {
36 | parent = parent.substring(0, parent.lastIndexOf(CoreConstants.DOT));
37 | }else{
38 | parent=StringUtils.EMPTY;
39 | }
40 |
41 | }
42 | }
43 | return dataInfo;
44 | }
45 |
46 |
47 | public static void flatPut(String key, Object value, Map map) {
48 | if (key.contains(CoreConstants.DOT)) {
49 | String firstItem = key.substring(0, key.indexOf(CoreConstants.DOT));
50 | String restItems = key.substring(key.indexOf(CoreConstants.DOT) + 1);
51 | if (map.containsKey(firstItem)) {
52 | flatPut(restItems, value, (Map) map.get(firstItem));
53 | } else {
54 | Map temp = new HashMap<>(0);
55 | map.put(firstItem, temp);
56 | flatPut(restItems, value, (Map) map.get(firstItem));
57 | }
58 | } else {
59 | map.put(key, value);
60 | }
61 | }
62 |
63 | public static Object flatGet(String key, Map map) {
64 | if (key.contains(CoreConstants.DOT)) {
65 | String firstItem = key.substring(0, key.indexOf(CoreConstants.DOT));
66 | String restItems = key.substring(key.indexOf(CoreConstants.DOT) + 1);
67 | if (map.containsKey(firstItem)) {
68 | return flatGet(restItems, (Map) map.get(firstItem));
69 | } else {
70 | return null;
71 | }
72 | } else {
73 | return map.get(key);
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/resources/es-plugin.properties:
--------------------------------------------------------------------------------
1 | plugin=io.github.iamazy.elasticsearch.dsl.plugin.SqlPlugin
2 | version=${project.version}
--------------------------------------------------------------------------------
/src/main/resources/plugin-descriptor.properties:
--------------------------------------------------------------------------------
1 | # elasticsearch-sql项目的描述
2 | description=${project.description}
3 |
4 | # elasticsearch-sql项目自己的版本,和es的版本没有关系
5 | version=${project.version}
6 |
7 | # 插件的名字
8 | name=${elasticsearch.plugin.name}
9 |
10 | classname=${elasticsearch.plugin.classname}
11 |
12 | java.version=1.8
13 |
14 | # es的版本,ctrl+鼠标点击 可以跳到pom文件看该参数的值
15 | elasticsearch.version=${elasticsearch.version}
--------------------------------------------------------------------------------
/src/main/resources/plugin-security.policy:
--------------------------------------------------------------------------------
1 | grant {
2 | // needed because of the hot reload functionality
3 | permission java.net.SocketPermission "*", "connect,resolve";
4 | };
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/DeleteTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | /**
8 | * @author iamazy
9 | * @date 2019/3/4
10 | * @descrition
11 | **/
12 | public class DeleteTest {
13 |
14 | @Test
15 | public void delete(){
16 |
17 | String sql="DELETE from fruits where match_all() limit 1100";
18 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
19 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
20 |
21 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toDelRequest().getSearchRequest()));
22 | }
23 |
24 | @Test
25 | public void query(){
26 | String sql="SELECT * FROM product.apple QUERY term(productName, 'iphone6s', 'boost:2.0f')";
27 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
28 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
29 |
30 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
31 | }
32 |
33 |
34 |
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/DescTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | /**
8 | * @author iamazy
9 | * @date 2019/5/5
10 | * @descrition
11 | **/
12 | public class DescTest {
13 |
14 | @Test
15 | public void test3(){
16 | String sql="desc device_info";
17 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
18 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/NestedAggTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | /**
8 | * @author iamazy
9 | * @date 2019/3/25
10 | * @descrition
11 | **/
12 | public class NestedAggTest {
13 |
14 |
15 | @Test
16 | public void nested2Agg(){
17 | String nested="select * from product where $product$apple.type='AirPod' group by nested(product)>(nested(product.apple)>(terms(product.apple.type, 20),terms(product.apple.name,2))) limit 0,0";
18 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
19 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(nested);
20 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
21 | }
22 |
23 | @Test
24 | public void nested3(){
25 | String sql="select * from regions group by terms(country)>terms(province)";
26 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
27 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
28 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
29 | }
30 |
31 | @Test
32 | public void geoDistanceAgg(){
33 | String sql="select * from regions group by geo_distance(distance#km,origin(0.0,11.0),range(1.0,3.0))";
34 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
35 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
36 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
37 | }
38 |
39 | @Test
40 | public void agg(){
41 | String sql="select * from apple group by terms(productName,10)>(terms(provider,10),cardinality(provider))";
42 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
43 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
44 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/ScoreTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | public class ScoreTest {
8 |
9 |
10 | @Test
11 | public void boostingTest(){
12 | String sql="select * from fruit query boosting(h#name='apple',h#weight>100,0.2)";
13 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
14 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
15 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
16 | }
17 |
18 | @Test
19 | public void functionScoreTest(){
20 | String sql="select * from fruit query function_score(h#name='a',script_score(h#naame='ddd','fsdfsdf0','a:1,b:2'),random_score(age>90,101092339,'date'),weight(a>1,3),weight(b<4,4),weight(c='aa',5),weight(d is not null,9))";
21 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
22 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
23 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/ScriptQueryTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | /**
8 | * @author iamazy
9 | * @date 2019/3/6
10 | * @descrition
11 | **/
12 | public class ScriptQueryTest {
13 |
14 |
15 | @Test
16 | public void scriptTest(){
17 | String sql="select * from search where script_query('if (ctx._source.user == \"kimchy\") {ctx._source.likes++;}','name:iamazy,age:23,gender:male')";
18 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
19 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
20 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/ScrollTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | /**
8 | * @author iamazy
9 | * @date 2019/3/25
10 | * @descrition
11 | **/
12 | public class ScrollTest {
13 |
14 |
15 | @Test
16 | public void scroll(){
17 |
18 | //scroll by 前面表示scroll id过期时间,后面表示scroll id
19 | String sql="select * from search order by lastModified routing by 'fdsfdsfdf' scroll by '2121m','fdsfdsfdsfsdfdsf' limit 20,10";
20 | ElasticSql2DslParser elasticSql2DslParser=new ElasticSql2DslParser();
21 | ElasticSqlParseResult elasticSqlParseResult = elasticSql2DslParser.parse(sql);
22 |
23 | System.out.println(elasticSqlParseResult.toPrettyDsl(elasticSqlParseResult.toRequest()));
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/io/github/iamazy/elasticsearch/dsl/sql/SqlParserSelectFieldTest.java:
--------------------------------------------------------------------------------
1 | package io.github.iamazy.elasticsearch.dsl.sql;
2 |
3 | import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticSqlParseResult;
4 | import io.github.iamazy.elasticsearch.dsl.sql.parser.ElasticSql2DslParser;
5 | import org.junit.Test;
6 |
7 | import java.util.Arrays;
8 |
9 | /**
10 | * @author iamazy
11 | * @date 2019/2/20
12 | * @descrition
13 | **/
14 | public class SqlParserSelectFieldTest {
15 |
16 | @Test
17 | public void testParseFromMethodSource(){
18 | String sql="select * from fruit query match(h#name,'苹果','prefix_length:21,boost:2.0f') and term(weight,80)";
19 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
20 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
21 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
22 | }
23 |
24 | @Test
25 | public void testHasParent(){
26 | String sql="select * from fruit where has_parent('vegetable',weight between 100 and 400)";
27 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
28 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
29 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
30 | }
31 |
32 | @Test
33 | public void testHasChild(){
34 | String sql="select `name*`,^age from fruit where has_child('apple',price in (10,20,30),1,4)";
35 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
36 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
37 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
38 | }
39 |
40 |
41 | /**
42 | * 高亮显示 在字段前面用h#标识
43 | */
44 | @Test
45 | public void testParseFlatTermsAgg(){
46 | String sql="select * from fruit where match(h#$aaaaa.bb,'fdsfdsfdsf') and fuzzy(h#bbb,'fdsfdf') and h#name is not null and color is not null group by terms(weight,5000),terms(category,100) limit 0,0";
47 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
48 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
49 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
50 | }
51 |
52 |
53 | @Test
54 | public void testHighlighter(){
55 | String sql="select * from fruit where h#$macInfo.name='0xsdfs' limit 0,0";
56 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
57 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
58 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
59 | }
60 |
61 | @Test
62 | public void testHighlighter2(){
63 | String sql="select * from fruit where match_phrase(name,'苹果') or match_phrase(h#$aaa$bbb.mac,'0x10192j') order by lastModified desc limit 0,10";
64 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
65 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
66 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
67 | }
68 |
69 | @Test
70 | public void test2(){
71 | String sql="select * from fruit where query_string('h#苹果','fields:weight*,name','analyzer:ik_smart,phrase_slop:1')";
72 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
73 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
74 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
75 | }
76 |
77 | @Test
78 | public void test3(){
79 | String sql="select * from `apple-aaa-01-.*` order by minPrice desc, advicePrice asc";
80 | ElasticSql2DslParser sql2DslParser=new ElasticSql2DslParser();
81 | ElasticSqlParseResult parseResult = sql2DslParser.parse(sql);
82 | System.out.println(parseResult.toPrettyDsl(parseResult.toRequest()));
83 | System.out.println(Arrays.toString(parseResult.toRequest().indices()));
84 | }
85 |
86 |
87 | }
88 |
--------------------------------------------------------------------------------