2 * angular-elastic-builder
4 * /src/services/QueryService.js
6 * This file is used to convert filters into queries, and vice versa
12 angular.module('angular-elastic-builder')
13 .factory('elasticQueryService', [
23 function toFilters(query, fieldMap) {
24 var filters = query.map(parseQueryGroup.bind(query, fieldMap));
28 function toQuery(filters, fieldMap) {
29 var query = filters.map(parseFilterGroup.bind(filters, fieldMap)).filter(function(item) {
35 function parseQueryGroup(fieldMap, group, truthy) {
36 if (truthy !== false) {
40 var key = Object.keys(group)[0],
46 type = typeMap[key] || 'item',
47 obj = getFilterTemplate(type);
52 obj.rules = group[key].map(parseQueryGroup.bind(group, fieldMap));
57 obj.field = group[key].field;
66 obj.field = Object.keys(group[key])[0];
67 var fieldData = fieldMap[Object.keys(group[key])[0]];
69 if (fieldData.type === 'multi') {
70 var vals = group[key][obj.field];
71 if (typeof vals === 'string') {
74 // MY CUSTOM MODIFICATION
75 obj.value = group[key][obj.field];
76 // obj.values = fieldData.choices.reduce(function(prev, choice) {
77 // prev[choice] = truthy === (group[key][obj.field].indexOf(choice) > -1);
81 obj.subType = truthy ? 'equals' : 'notEquals';
82 obj.value = group[key][obj.field];
84 if (typeof obj.value === 'number') {
85 obj.subType = 'boolean';
90 obj.field = Object.keys(group[key])[0];
91 obj.subType = Object.keys(group[key][obj.field])[0];
92 obj.value = group[key][obj.field][obj.subType];
95 obj = parseQueryGroup(fieldMap, group[key].filter, false);
98 obj.field = Object.keys(group[key])[0];
105 function parseFilterGroup(fieldMap, group) {
107 if (group.type === 'group') {
108 obj[group.subType] = group.rules.map(parseFilterGroup.bind(group, fieldMap)).filter(function(item) {
114 var fieldName = group.field;
115 var fieldData = fieldMap[fieldName];
121 switch (fieldData.type) {
124 if (fieldData.subType === 'boolean') {
125 group.subType = 'boolean';
128 if (!group.subType) {
131 switch (group.subType) {
134 if (group.value === undefined) {
138 obj.term[fieldName] = group.value;
141 if (group.value === undefined) {
149 obj.not.filter.term[fieldName] = group.value;
162 throw new Error('unexpected subtype ' + group.subType);
168 obj.range[fieldName] = {};
169 obj.range[fieldName][group.subType] = group.value;
173 if (group.subType === 'exists') {
177 } else if (group.subType === 'notExists') {
182 throw new Error('unexpected subtype');
189 obj.terms[fieldName] = group.value;
190 // obj.terms[fieldName] = Object.keys(group.values || {}).reduce(function(prev, key) {
191 // if (group.values[key]) prev.push(key);
198 throw new Error('unexpected type');
204 function getFilterTemplate(type) {
223 return angular.copy(templates[type]);