2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.aai.sa.searchdbabstraction.searchapi;
23 import com.fasterxml.jackson.annotation.JsonProperty;
24 import java.util.Arrays;
26 import java.util.List;
27 import java.util.concurrent.atomic.AtomicBoolean;
30 * This class represents a simple term query.
32 * <p>A term query takes an operator, a field to apply the query to and a value to match
33 * against the query contents.
35 * <p>Valid operators include:
37 * <li> match - Field must contain the supplied value to produce a match. </li>
38 * <li> not-match - Field must NOT contain the supplied value to produce a match. </li>
40 * The following examples illustrate the structure of a few variants of the
44 * // Single Field Match Query:
46 * "match": {"field": "searchTags", "value": "abcd"}
49 * // Single Field Not-Match query:
51 * "not-match": {"field": "searchTags", "value": "efgh"}
56 * // Multi Field Match Query With A Single Value:
58 * "match": {"field": "entityType searchTags", "value": "pserver"}
61 * // Multi Field Match Query With Multiple Values:
63 * "match": {"field": "entityType searchTags", "value": "pserver tenant"}
67 public class TermQuery {
70 * The name of the field to apply the term query to.
75 * The value which the field must contain in order to have a match.
80 * For multi field queries only. Determines the rules for whether or not a document matches
81 * the query, as follows:
83 * <p>"and" - At least one occurrence of every supplied value must be present in any of the
86 * <p>"or" - At least one occurrence of any of the supplied values must be present in any of
87 * the supplied fields.
89 private String operator;
91 @JsonProperty("analyzer")
92 private String searchAnalyzer;
95 public String getField() {
99 public void setField(String field) {
103 public Object getValue() {
107 public void setValue(Object value) {
111 private boolean isNumericValue() {
112 return ((value instanceof Integer) || (value instanceof Double));
115 public String getOperator() {
119 public void setOperator(String operator) {
120 this.operator = operator;
123 public String getSearchAnalyzer() {
124 return searchAnalyzer;
127 public void setSearchAnalyzer(String searchAnalyzer) {
128 this.searchAnalyzer = searchAnalyzer;
132 * This method returns a string which represents this query in syntax
133 * that is understandable by ElasticSearch and is suitable for inclusion
134 * in an ElasticSearch query string.
136 * @return - ElasticSearch syntax string.
138 public String toElasticSearch() {
140 StringBuilder sb = new StringBuilder();
144 // Are we generating a multi field query?
145 if (isMultiFieldQuery()) {
147 // For multi field queries, we have to be careful about how we handle
148 // nested fields, so check to see if any of the specified fields are
150 if (field.contains(".")) {
152 // Build the equivalent of a multi match query across one or more nested fields.
153 toElasticSearchNestedMultiMatchQuery(sb);
157 // Build a real multi match query, since we don't need to worry about nested fields.
158 toElasticSearchMultiFieldQuery(sb);
162 // Single field query.
164 // Add the necessary wrapping if this is a query against a nested field.
165 if (fieldIsNested(field)) {
166 sb.append("{\"nested\": { \"path\": \"").append(pathForNestedField(field))
167 .append("\", \"query\": ");
171 toElasticSearchSingleFieldQuery(sb);
173 if (fieldIsNested(field)) {
180 return sb.toString();
185 * Determines whether or not the client has specified a term query with
188 * @return - true if the query is referencing multiple fields, false, otherwise.
190 private boolean isMultiFieldQuery() {
192 return (field.split(" ").length > 1);
197 * Constructs a single field term query in ElasticSearch syntax.
199 * @param sb - The string builder to assemble the query string with.
200 * @return - The single term query.
202 private void toElasticSearchSingleFieldQuery(StringBuilder sb) {
204 sb.append("\"term\": {\"").append(field).append("\" : ");
206 // For numeric values, don't enclose the value in quotes.
207 if (!isNumericValue()) {
208 sb.append("\"").append(value).append("\"");
218 * Constructs a multi field query in ElasticSearch syntax.
220 * @param sb - The string builder to assemble the query string with.
221 * @return - The multi field query.
223 private void toElasticSearchMultiFieldQuery(StringBuilder sb) {
225 sb.append("\"multi_match\": {");
227 sb.append("\"query\": \"").append(value).append("\", ");
228 sb.append("\"type\": \"cross_fields\",");
229 sb.append("\"fields\": [");
231 List<String> fields = Arrays.asList(field.split(" "));
232 AtomicBoolean firstField = new AtomicBoolean(true);
233 for (String f : fields) {
234 if (!firstField.compareAndSet(true, false)) {
237 sb.append("\"").append(f.trim()).append("\"");
241 sb.append("\"operator\": \"").append((operator != null)
242 ? operator.toLowerCase() : "and").append("\"");
244 if (searchAnalyzer != null) {
245 sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\"");
253 * Constructs the equivalent of an ElasticSearch multi match query across
254 * multiple nested fields.
256 * <p>Since ElasticSearch doesn't really let you do that, we have to be clever
257 * and construct an equivalent query using boolean operators to produce
260 * @param sb - The string builder to use to build the query.
262 public void toElasticSearchNestedMultiMatchQuery(StringBuilder sb) {
264 // Break out our whitespace delimited list of fields and values into a actual lists.
265 List<String> fields = Arrays.asList(field.split(" "));
266 List<String> values = Arrays.asList(((String) value).split(" ")); // GDF: revisit this cast.
268 sb.append("\"bool\": {");
270 if (operator != null) {
272 if (operator.toLowerCase().equals("and")) {
273 sb.append("\"must\": [");
274 } else if (operator.toLowerCase().equals("or")) {
275 sb.append("\"should\": [");
279 sb.append("\"must\": [");
282 AtomicBoolean firstField = new AtomicBoolean(true);
283 for (String f : fields) {
285 if (!firstField.compareAndSet(true, false)) {
291 // Is this a nested field?
292 if (fieldIsNested(f)) {
294 sb.append("\"nested\": {");
295 sb.append("\"path\": \"").append(pathForNestedField(f)).append("\", ");
296 sb.append("\"query\": ");
299 sb.append("{\"bool\": {");
300 sb.append("\"should\": [");
302 AtomicBoolean firstValue = new AtomicBoolean(true);
303 for (String v : values) {
304 if (!firstValue.compareAndSet(true, false)) {
307 sb.append("{\"match\": { \"");
308 sb.append(f).append("\": {\"query\": \"").append(v).append("\"");
310 if (searchAnalyzer != null) {
311 sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\"");
319 if (fieldIsNested(f)) {
333 public String toString() {
334 return "field: " + field + ", value: " + value + " (" + value.getClass().getName() + ")";
337 public boolean fieldIsNested(String field) {
338 return field.contains(".");
341 public String pathForNestedField(String field) {
342 int index = field.lastIndexOf('.');
343 return field.substring(0, index);