|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * |
| 4 | + * The OpenSearch Contributors require contributions made to |
| 5 | + * this file be licensed under the Apache-2.0 license or a |
| 6 | + * compatible open source license. |
| 7 | + */ |
| 8 | + |
| 9 | +package org.opensearch.index.query; |
| 10 | + |
| 11 | +import org.apache.lucene.search.Query; |
| 12 | +import org.opensearch.common.xcontent.LoggingDeprecationHandler; |
| 13 | +import org.opensearch.common.xcontent.XContentFactory; |
| 14 | +import org.opensearch.common.xcontent.XContentType; |
| 15 | +import org.opensearch.common.xcontent.json.JsonXContent; |
| 16 | +import org.opensearch.core.common.io.stream.StreamInput; |
| 17 | +import org.opensearch.core.common.io.stream.StreamOutput; |
| 18 | +import org.opensearch.core.xcontent.XContentBuilder; |
| 19 | +import org.opensearch.core.xcontent.XContentParser; |
| 20 | + |
| 21 | +import java.io.IOException; |
| 22 | +import java.util.Map; |
| 23 | +import java.util.Objects; |
| 24 | +import java.util.stream.Collectors; |
| 25 | + |
| 26 | +import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; |
| 27 | + |
| 28 | +/** |
| 29 | + * A query builder that constructs a query based on a template and context variables. |
| 30 | + * This query is designed to be rewritten with variables from search processors. |
| 31 | + */ |
| 32 | + |
| 33 | +public class TemplateQueryBuilder extends AbstractQueryBuilder<TemplateQueryBuilder> { |
| 34 | + public static final String NAME = "template"; |
| 35 | + public static final String queryName = "template"; |
| 36 | + private final Map<String, Object> content; |
| 37 | + |
| 38 | + /** |
| 39 | + * Constructs a new TemplateQueryBuilder with the given content. |
| 40 | + * |
| 41 | + * @param content The template content as a map. |
| 42 | + */ |
| 43 | + public TemplateQueryBuilder(Map<String, Object> content) { |
| 44 | + this.content = content; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Creates a TemplateQueryBuilder from XContent. |
| 49 | + * |
| 50 | + * @param parser The XContentParser to read from. |
| 51 | + * @return A new TemplateQueryBuilder instance. |
| 52 | + * @throws IOException If there's an error parsing the content. |
| 53 | + */ |
| 54 | + public static TemplateQueryBuilder fromXContent(XContentParser parser) throws IOException { |
| 55 | + return new TemplateQueryBuilder(parser.map()); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Constructs a TemplateQueryBuilder from a stream input. |
| 60 | + * |
| 61 | + * @param in The StreamInput to read from. |
| 62 | + * @throws IOException If there's an error reading from the stream. |
| 63 | + */ |
| 64 | + public TemplateQueryBuilder(StreamInput in) throws IOException { |
| 65 | + super(in); |
| 66 | + this.content = in.readMap(); |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + protected void doWriteTo(StreamOutput out) throws IOException { |
| 71 | + out.writeMap(content); |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + protected void doXContent(XContentBuilder builder, Params params) throws IOException { |
| 76 | + builder.field(NAME, content); |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + protected Query doToQuery(QueryShardContext context) throws IOException { |
| 81 | + throw new IllegalStateException( |
| 82 | + "Template queries cannot be converted directly to a query. Template Query must be rewritten first during doRewrite." |
| 83 | + ); |
| 84 | + } |
| 85 | + |
| 86 | + @Override |
| 87 | + protected boolean doEquals(TemplateQueryBuilder other) { |
| 88 | + return Objects.equals(this.content, other.content); |
| 89 | + } |
| 90 | + |
| 91 | + @Override |
| 92 | + protected int doHashCode() { |
| 93 | + return Objects.hash(content); |
| 94 | + } |
| 95 | + |
| 96 | + @Override |
| 97 | + public String getWriteableName() { |
| 98 | + return NAME; |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Gets the content of this template query. |
| 103 | + * |
| 104 | + * @return The template content as a map. |
| 105 | + */ |
| 106 | + public Map<String, Object> getContent() { |
| 107 | + return content; |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Rewrites the template query by substituting variables from the context. |
| 112 | + * |
| 113 | + * @param queryRewriteContext The context for query rewriting. |
| 114 | + * @return A rewritten QueryBuilder. |
| 115 | + * @throws IOException If there's an error during rewriting. |
| 116 | + */ |
| 117 | + @Override |
| 118 | + protected QueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) throws IOException { |
| 119 | + // the queryRewrite is expected at QueryCoordinator level |
| 120 | + QueryCoordinatorContext queryCoordinatorContext = queryRewriteContext.convertToCoordinatorContext(); |
| 121 | + if (queryCoordinatorContext == null) { |
| 122 | + throw new IllegalStateException( |
| 123 | + "Template Query must be rewritten at the coordinator node. Rewriting at shard level is not supported." |
| 124 | + ); |
| 125 | + } |
| 126 | + |
| 127 | + Map<String, Object> contextVariables = queryCoordinatorContext.getContextVariables(); |
| 128 | + String queryString; |
| 129 | + |
| 130 | + try (XContentBuilder builder = XContentFactory.jsonBuilder()) { |
| 131 | + builder.map(this.content); |
| 132 | + queryString = builder.toString(); |
| 133 | + } |
| 134 | + |
| 135 | + // Convert Map<String, Object> to Map<String, String> with proper JSON escaping |
| 136 | + Map<String, String> variablesMap = null; |
| 137 | + if (contextVariables != null) { |
| 138 | + variablesMap = contextVariables.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> { |
| 139 | + try { |
| 140 | + return JsonXContent.contentBuilder().value(entry.getValue()).toString(); |
| 141 | + } catch (IOException e) { |
| 142 | + throw new RuntimeException("Error converting contextVariables to JSON string", e); |
| 143 | + } |
| 144 | + })); |
| 145 | + } |
| 146 | + String newQueryContent = replaceVariables(queryString, variablesMap); |
| 147 | + |
| 148 | + try { |
| 149 | + XContentParser parser = XContentType.JSON.xContent() |
| 150 | + .createParser(queryCoordinatorContext.getXContentRegistry(), LoggingDeprecationHandler.INSTANCE, newQueryContent); |
| 151 | + |
| 152 | + ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser); |
| 153 | + |
| 154 | + QueryBuilder newQueryBuilder = parseInnerQueryBuilder(parser); |
| 155 | + |
| 156 | + return newQueryBuilder; |
| 157 | + |
| 158 | + } catch (Exception e) { |
| 159 | + throw new IllegalArgumentException("Failed to rewrite template query: " + newQueryContent, e); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + private String replaceVariables(String template, Map<String, String> variables) { |
| 164 | + if (template == null || template.equals("null")) { |
| 165 | + throw new IllegalArgumentException("Template string cannot be null. A valid template must be provided."); |
| 166 | + } |
| 167 | + if (template.isEmpty() || template.equals("{}")) { |
| 168 | + throw new IllegalArgumentException("Template string cannot be empty. A valid template must be provided."); |
| 169 | + } |
| 170 | + if (variables == null || variables.isEmpty()) { |
| 171 | + return template; |
| 172 | + } |
| 173 | + |
| 174 | + StringBuilder result = new StringBuilder(); |
| 175 | + int start = 0; |
| 176 | + while (true) { |
| 177 | + int startVar = template.indexOf("\"${", start); |
| 178 | + if (startVar == -1) { |
| 179 | + result.append(template.substring(start)); |
| 180 | + break; |
| 181 | + } |
| 182 | + result.append(template, start, startVar); |
| 183 | + int endVar = template.indexOf("}\"", startVar); |
| 184 | + if (endVar == -1) { |
| 185 | + throw new IllegalArgumentException("Unclosed variable in template: " + template.substring(startVar)); |
| 186 | + } |
| 187 | + String varName = template.substring(startVar + 3, endVar); |
| 188 | + String replacement = variables.get(varName); |
| 189 | + if (replacement == null) { |
| 190 | + throw new IllegalArgumentException("Variable not found: " + varName); |
| 191 | + } |
| 192 | + result.append(replacement); |
| 193 | + start = endVar + 2; |
| 194 | + } |
| 195 | + return result.toString(); |
| 196 | + } |
| 197 | + |
| 198 | +} |
0 commit comments