aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQuery.java
blob: b84fe53167179a00584b77eff80f3bf1495cd5b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 Amdocs
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.sa.searchdbabstraction.searchapi;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This class represents a simple term query.
 *
 * <p>A term query takes an operator, a field to apply the query to and a value to match
 * against the query contents.
 *
 * <p>Valid operators include:
 * <ul>
 * <li> match - Field must contain the supplied value to produce a match. </li>
 * <li> not-match - Field must NOT contain the supplied value to produce a match. </li>
 * </ul>
 * The following examples illustrate the structure of a few variants of the
 * term query:
 *
 * <p><pre>
 *     // Single Field Match Query:
 *     {
 *         "match": {"field": "searchTags", "value": "abcd"}
 *     }
 *
 *     // Single Field Not-Match query:
 *     {
 *         "not-match": {"field": "searchTags", "value": "efgh"}
 *     }
 * </pre>
 *
 * <p><pre>
 *     // Multi Field Match Query With A Single Value:
 *     {
 *         "match": {"field": "entityType searchTags", "value": "pserver"}
 *     }
 *
 *     // Multi Field Match Query With Multiple Values:
 *     {
 *         "match": {"field": "entityType searchTags", "value": "pserver tenant"}
 *     }
 * </pre>
 */
public class TermQuery {

  /**
   * The name of the field to apply the term query to.
   */
  private String field;

  /**
   * The value which the field must contain in order to have a match.
   */
  private Object value;

  /**
   * For multi field queries only.  Determines the rules for whether or not a document matches
   * the query, as follows:
   *
   * <p>"and" - At least one occurrence of every supplied value must be present in any of the
   * supplied fields.
   *
   * <p>"or"  - At least one occurrence of any of the supplied values must be present in any of
   * the supplied fields.
   */
  private String operator;

  @JsonProperty("analyzer")
  private String searchAnalyzer;


  public String getField() {
    return field;
  }

  public void setField(String field) {
    this.field = field;
  }

  public Object getValue() {
    return value;
  }

  public void setValue(Object value) {
    this.value = value;
  }

  private boolean isNumericValue() {
    return ((value instanceof Integer) || (value instanceof Double));
  }

  public String getOperator() {
    return operator;
  }

  public void setOperator(String operator) {
    this.operator = operator;
  }

  public String getSearchAnalyzer() {
    return searchAnalyzer;
  }

  public void setSearchAnalyzer(String searchAnalyzer) {
    this.searchAnalyzer = searchAnalyzer;
  }

  /**
   * This method returns a string which represents this query in syntax
   * that is understandable by ElasticSearch and is suitable for inclusion
   * in an ElasticSearch query string.
   *
   * @return - ElasticSearch syntax string.
   */
  public String toElasticSearch() {

    StringBuilder sb = new StringBuilder();

    sb.append("{");

    // Are we generating a multi field query?
    if (isMultiFieldQuery()) {

      // For multi field queries, we have to be careful about how we handle
      // nested fields, so check to see if any of the specified fields are
      // nested.
      if (field.contains(".")) {

        // Build the equivalent of a multi match query across one or more nested fields.
        toElasticSearchNestedMultiMatchQuery(sb);

      } else {

        // Build a real multi match query, since we don't need to worry about nested fields.
        toElasticSearchMultiFieldQuery(sb);
      }
    } else {

      // Single field query.

      // Add the necessary wrapping if this is a query against a nested field.
      if (fieldIsNested(field)) {
        sb.append("{\"nested\": { \"path\": \"").append(pathForNestedField(field))
            .append("\", \"query\": ");
      }

      // Build the query.
      toElasticSearchSingleFieldQuery(sb);

      if (fieldIsNested(field)) {
        sb.append("}}");
      }
    }

    sb.append("}");

    return sb.toString();
  }


  /**
   * Determines whether or not the client has specified a term query with
   * multiple fields.
   *
   * @return - true if the query is referencing multiple fields, false, otherwise.
   */
  private boolean isMultiFieldQuery() {

    return (field.split(" ").length > 1);
  }


  /**
   * Constructs a single field term query in ElasticSearch syntax.
   *
   * @param sb - The string builder to assemble the query string with.
   * @return - The single term query.
   */
  private void toElasticSearchSingleFieldQuery(StringBuilder sb) {

    sb.append("\"term\": {\"").append(field).append("\" : ");

    // For numeric values, don't enclose the value in quotes.
    if (!isNumericValue()) {
      sb.append("\"").append(value).append("\"");
    } else {
      sb.append(value);
    }

    sb.append("}");
  }


  /**
   * Constructs a multi field query in ElasticSearch syntax.
   *
   * @param sb - The string builder to assemble the query string with.
   * @return - The multi field query.
   */
  private void toElasticSearchMultiFieldQuery(StringBuilder sb) {

    sb.append("\"multi_match\": {");

    sb.append("\"query\": \"").append(value).append("\", ");
    sb.append("\"type\": \"cross_fields\",");
    sb.append("\"fields\": [");

    List<String> fields = Arrays.asList(field.split(" "));
    AtomicBoolean firstField = new AtomicBoolean(true);
    for (String f : fields) {
      if (!firstField.compareAndSet(true, false)) {
        sb.append(", ");
      }
      sb.append("\"").append(f.trim()).append("\"");
    }
    sb.append("],");

    sb.append("\"operator\": \"").append((operator != null)
        ? operator.toLowerCase() : "and").append("\"");

    if (searchAnalyzer != null) {
      sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\"");
    }

    sb.append("}");
  }


  /**
   * Constructs the equivalent of an ElasticSearch multi match query across
   * multiple nested fields.
   *
   * <p>Since ElasticSearch doesn't really let you do that, we have to be clever
   * and construct an equivalent query using boolean operators to produce
   * the same result.
   *
   * @param sb - The string builder to use to build the query.
   */
  public void toElasticSearchNestedMultiMatchQuery(StringBuilder sb) {

    // Break out our whitespace delimited list of fields and values into a actual lists.
    List<String> fields = Arrays.asList(field.split(" "));
    List<String> values = Arrays.asList(((String) value).split(" ")); // GDF: revisit this cast.

    sb.append("\"bool\": {");

    if (operator != null) {

      if (operator.toLowerCase().equals("and")) {
        sb.append("\"must\": [");
      } else if (operator.toLowerCase().equals("or")) {
        sb.append("\"should\": [");
      }

    } else {
      sb.append("\"must\": [");
    }

    AtomicBoolean firstField = new AtomicBoolean(true);
    for (String f : fields) {

      if (!firstField.compareAndSet(true, false)) {
        sb.append(", ");
      }

      sb.append("{ ");

      // Is this a nested field?
      if (fieldIsNested(f)) {

        sb.append("\"nested\": {");
        sb.append("\"path\": \"").append(pathForNestedField(f)).append("\", ");
        sb.append("\"query\": ");
      }

      sb.append("{\"bool\": {");
      sb.append("\"should\": [");

      AtomicBoolean firstValue = new AtomicBoolean(true);
      for (String v : values) {
        if (!firstValue.compareAndSet(true, false)) {
          sb.append(", ");
        }
        sb.append("{\"match\": { \"");
        sb.append(f).append("\": {\"query\": \"").append(v).append("\"");

        if (searchAnalyzer != null) {
          sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\"");
        }
        sb.append("}}}");
      }

      sb.append("]");
      sb.append("}");

      if (fieldIsNested(f)) {
        sb.append("}");
        sb.append("}");
      }

      sb.append("}");
    }

    sb.append("]");
    sb.append("}");
  }


  @Override
  public String toString() {
    return "field: " + field + ", value: " + value + " (" + value.getClass().getName() + ")";
  }

  public boolean fieldIsNested(String field) {
    return field.contains(".");
  }

  public String pathForNestedField(String field) {
    int index = field.lastIndexOf('.');
    return field.substring(0, index);
  }
}