summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatement.java
blob: 11eee1e0779370b255485c8b0798e479fd989e3f (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
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017 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=========================================================
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */
package org.onap.aai.sa.searchdbabstraction.searchapi;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.radeox.util.logging.Logger;

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

/**
 * This class represents the structure of a search statement.
 *
 * <p>The expected JSON structure to represent a search statement is as follows:
 *
 * <p><pre>
 *     {
 *         "results-start": int,  - Optional: index of starting point in result set.
 *         "results-size": int,   - Optional: maximum number of documents to include in result set.
 *
 *         "filter": {
 *             { filter structure - see {@link Filter} }
 *         },
 *
 *         "queries": [
 *             { query structure - see {@link QueryStatement} },
 *             { query structure - see {@link QueryStatement} },
 *                              .
 *                              .
 *             { query structure - see {@link QueryStatement} },
 *         ],
 *
 *         "aggregations": [
 *             { aggregation structure - see {@link AggregationStatement} },
 *             { aggregation structure - see {@link AggregationStatement} },
 *                              .
 *                              .
 *             { aggregation structure - see {@link AggregationStatement} },
 *         ]
 *     }
 * </pre>
 */
public class SearchStatement {

  /**
   * Defines the filters that should be applied before running the
   * actual queries.  This is optional.
   */
  private Filter filter;

  /**
   * The list of queries to be applied to the document store.
   */
  private Query[] queries;

  /**
   * The list of aggregations to be applied to the search
   */
  private Aggregation[] aggregations;

  /**
   * Defines the sort criteria to apply to the query result set.
   * This is optional.
   */
  private Sort sort;

  @JsonProperty("results-start")
  private Integer resultsStart;

  @JsonProperty("results-size")
  private Integer size;

  public Filter getFilter() {
    return filter;
  }

  public void setFilter(Filter filter) {
    this.filter = filter;
  }

  public Query[] getQueries() {
    return queries;
  }

  public void setQueries(Query[] queries) {
    this.queries = queries;
  }

  public Sort getSort() {
    return sort;
  }

  public void setSort(Sort sort) {
    this.sort = sort;
  }

  public boolean isFiltered() {
    return filter != null;
  }

  public Aggregation[] getAggregations() {
    return aggregations;
  }

  public void setAggregations(Aggregation[] aggregations) {
    this.aggregations = aggregations;
  }

  public boolean hasAggregations() {
    return aggregations != null && aggregations.length > 0;
  }

  public Integer getFrom() {
    return resultsStart;
  }

  public void setFrom(Integer from) {
    this.resultsStart = from;
  }

  public Integer getSize() {
    return size;
  }

  public void setSize(Integer size) {
    this.size = size;
  }

  /**
   * This method returns a string which represents this statement 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();
    List<QueryStatement> notMatchQueries = new ArrayList<QueryStatement>();
    List<QueryStatement> mustQueries = new ArrayList<QueryStatement>();
    List<QueryStatement> shouldQueries = new ArrayList<QueryStatement>();

    createQueryLists(queries, mustQueries, shouldQueries, notMatchQueries);

    sb.append("{");

    sb.append("\"version\": true,");

    // If the client has specified an index into the results for the first
    // document in the result set then include that in the ElasticSearch
    // query.
    if (resultsStart != null) {
      sb.append("\"from\": ").append(resultsStart).append(", ");
    }

    // If the client has specified a maximum number of documents to be returned
    // in the result set then include that in the ElasticSearch query.
    if (size != null) {
      sb.append("\"size\": ").append(size).append(", ");
    }

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

    sb.append("\"must\": [");
    AtomicBoolean firstQuery = new AtomicBoolean(true);
    for (QueryStatement query : mustQueries) {

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

      sb.append(query.toElasticSearch());
    }
    sb.append("], ");

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

    firstQuery = new AtomicBoolean(true);
    for (QueryStatement query : shouldQueries) {

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

      sb.append(query.toElasticSearch());
    }

    sb.append("],"); // close should list

    sb.append("\"must_not\": [");
    firstQuery.set(true);
    for (QueryStatement query : notMatchQueries) {
      sb.append(query.toElasticSearch());
    }
    sb.append("]");

    // Add the filter stanza, if one is required.
    if (isFiltered()) {
      sb.append(", \"filter\": ").append(filter.toElasticSearch());
    }

    sb.append("}"); // close bool clause
    sb.append("}"); // close query clause

    // Add the sort directive, if one is required.
    if (sort != null) {
      sb.append(", \"sort\": ").append(sort.toElasticSearch());
    }

    // Add aggregations
    if (hasAggregations()) {
      sb.append(", \"aggs\": {");

      for (int i = 0; i < aggregations.length; i++) {
        if (i > 0) {
          sb.append(",");
        }
        sb.append(aggregations[i].toElasticSearch());
      }

      sb.append("}");
    }

    sb.append("}");

    Logger.debug("Generated raw ElasticSearch query statement: " + sb.toString());
    return sb.toString();
  }

  private void createQueryLists(Query[] queries, List<QueryStatement> mustList,
                                List<QueryStatement> mayList, List<QueryStatement> mustNotList) {

    for (Query query : queries) {

      if (query.isMust()) {

        if (query.getQueryStatement().isNotMatch()) {
          mustNotList.add(query.getQueryStatement());
        } else {
          mustList.add(query.getQueryStatement());
        }
      } else {

        if (query.getQueryStatement().isNotMatch()) {
          mustNotList.add(query.getQueryStatement());
        } else {
          mayList.add(query.getQueryStatement());
        }
      }
    }
  }


  @Override
  public String toString() {

    StringBuilder sb = new StringBuilder();

    sb.append("SEARCH STATEMENT: {");

    if (size != null) {
      sb.append("from: ").append(resultsStart).append(", size: ").append(size).append(", ");
    }

    if (filter != null) {
      sb.append("filter: ").append(filter.toString()).append(", ");
    }

    sb.append("queries: [");
    AtomicBoolean firstQuery = new AtomicBoolean(true);
    if (queries != null) {
      for (Query query : queries) {

        if (!firstQuery.compareAndSet(true, false)) {
          sb.append(", ");
        }
        sb.append(query.toString());
      }
    }
    sb.append("]");

    sb.append("aggregations: [");
    firstQuery = new AtomicBoolean(true);

    if (aggregations != null) {
      for (Aggregation agg : aggregations) {

        if (!firstQuery.compareAndSet(true, false)) {
          sb.append(", ");
        }
        sb.append(agg.toString());
      }
    }
    sb.append("]");

    sb.append("]}");

    return sb.toString();
  }

}