search.ko.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. function magicLayout(vm) {
  17. loadLayout(vm, vm.initial.layout);
  18. $(document).trigger("magicLayout");
  19. }
  20. function loadLayout(viewModel, json_layout) {
  21. var _columns = [];
  22. $(json_layout).each(function (cnt, json_col) {
  23. var _rows = [];
  24. $(json_col.rows).each(function (rcnt, json_row) {
  25. var row = new Row([], viewModel);
  26. $(json_row.widgets).each(function (wcnt, widget) {
  27. row.addWidget(new Widget({
  28. size:widget.size,
  29. id: widget.id,
  30. name: widget.name,
  31. widgetType: widget.widgetType,
  32. properties: widget.properties,
  33. offset: widget.offset,
  34. loading: true,
  35. vm: viewModel
  36. }));
  37. });
  38. _rows.push(row);
  39. });
  40. var column = new Column(json_col.size, _rows);
  41. _columns = _columns.concat(column);
  42. });
  43. viewModel.columns(_columns);
  44. }
  45. // End dashboard lib
  46. var Query = function (vm, query) {
  47. var self = this;
  48. self.qs = ko.mapping.fromJS(query.qs);
  49. self.fqs = ko.mapping.fromJS(query.fqs);
  50. self.start = ko.mapping.fromJS(query.start);
  51. var defaultMultiqGroup = {'id': 'query', 'label': 'query'};
  52. self.multiqs = ko.computed(function () { // List of widgets supporting multiqs
  53. var histogram_id = vm.collection.getHistogramFacet();
  54. return [defaultMultiqGroup].concat(
  55. $.map($.grep(self.fqs(), function(fq, i) {
  56. return (fq.type() == 'field' || fq.type() == 'range') && (histogram_id == null || histogram_id.id() != fq.id());
  57. }), function(fq) { return {'id': fq.id(), 'label': fq.field()} })
  58. );
  59. });
  60. self.selectedMultiq = ko.observable('query');
  61. self.getFacetFilter = function(widget_id) {
  62. var _fq = null;
  63. $.each(self.fqs(), function (index, fq) {
  64. if (fq.id() == widget_id) {
  65. _fq = fq;
  66. return false;
  67. }
  68. });
  69. return _fq;
  70. };
  71. self.getMultiq = ko.computed(function () {
  72. if (self.selectedMultiq()) {
  73. if (self.selectedMultiq() == 'query') {
  74. if (self.qs().length >= 2) {
  75. return 'query';
  76. }
  77. } else {
  78. var facet = self.getFacetFilter(self.selectedMultiq());
  79. if (facet && facet.filter().length > 0) {
  80. return 'facet';
  81. }
  82. }
  83. }
  84. return null;
  85. });
  86. self.addQ = function (data) {
  87. self.qs.push(ko.mapping.fromJS({'q': ''}));
  88. };
  89. self.removeQ = function (query) {
  90. self.qs.remove(query);
  91. };
  92. self.selectedMultiq.subscribe(function () { // To keep below the computed objects!
  93. vm.search();
  94. });
  95. self.toggleFacet = function (data) {
  96. var fq = self.getFacetFilter(data.widget_id);
  97. if (fq == null) {
  98. self.fqs.push(ko.mapping.fromJS({
  99. 'id': data.widget_id,
  100. 'field': data.facet.cat,
  101. 'filter': [{'exclude': data.exclude ? true : false, 'value': data.facet.value}],
  102. 'type': 'field'
  103. }));
  104. } else {
  105. $.each(self.fqs(), function (index, fq) {
  106. if (fq.id() == data.widget_id) {
  107. var f = $.grep(fq.filter(), function(f) { return f.value() == data.facet.value; });
  108. if (f.length > 0) {
  109. fq.filter.remove(f[0]);
  110. if (fq.filter().length == 0) {
  111. self.fqs.remove(fq);
  112. }
  113. } else {
  114. fq.filter.push(ko.mapping.fromJS({'exclude': data.exclude ? true : false, 'value': data.facet.value}));
  115. }
  116. }
  117. });
  118. }
  119. self.start(0);
  120. vm.search();
  121. }
  122. self.togglePivotFacet = function (data) {
  123. data.facet.cat = data.facet.fq_fields;
  124. data.facet.value = data.facet.fq_values;
  125. self.toggleFacet(data);
  126. }
  127. function _toggleSingleTermFacet(data, exclude) {
  128. var fq = getFilterByField(data.val.cat);
  129. var id;
  130. if (fq) {
  131. id = fq.id();
  132. } else {
  133. id = UUID();
  134. }
  135. self.toggleFacet({'widget_id': id, 'facet': {'cat': data.val.cat, 'value': data.val.value}, 'exclude': exclude});
  136. vm.search();
  137. }
  138. self.addSingleTermFacet = function(data) {
  139. _toggleSingleTermFacet(data, false);
  140. }
  141. self.removeSingleTermFacet = function(data) {
  142. _toggleSingleTermFacet(data, true);
  143. }
  144. self.selectRangeFacet = function (data) {
  145. if (data.force != undefined) {
  146. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id, 'dontZoomOut': true}));
  147. }
  148. var fq = self.getFacetFilter(data.widget_id);
  149. if (fq == null) {
  150. self.fqs.push(ko.mapping.fromJS({
  151. 'id': data.widget_id,
  152. 'field': data.cat,
  153. 'filter': [{'exclude': data.exclude ? true : false, 'value': data.from}],
  154. 'properties': [{'from': data.from, 'to': data.to}],
  155. 'type': 'range'
  156. }));
  157. } else {
  158. var f = $.grep(fq.filter(), function(f) { return f.value() == data.from; });
  159. if (f.length > 0) { // Unselect
  160. fq.filter.remove(f[0]);
  161. $.each(fq.properties(), function (index, prop) {
  162. if (prop && prop.from() == data.from) {
  163. fq.properties.remove(prop);
  164. }
  165. });
  166. if (fq.filter().length == 0) {
  167. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  168. }
  169. } else {
  170. fq.filter.push(ko.mapping.fromJS({'exclude': data.exclude ? true : false, 'value': data.from}));
  171. fq.properties.push(ko.mapping.fromJS({'from': data.from, 'to': data.to}));
  172. }
  173. }
  174. self.start(0);
  175. if (data.no_refresh == undefined) {
  176. vm.search();
  177. }
  178. };
  179. function getFilterByField(field) {
  180. var _fq = null;
  181. $.each(self.fqs(), function (index, fq) {
  182. if (fq.field() == field && fq.id().indexOf('***') == 0) {
  183. _fq= fq;
  184. return false;
  185. }
  186. });
  187. return _fq;
  188. };
  189. self.removeFilter = function (data) {
  190. var found = false;
  191. $.each(self.fqs(), function (index, fq) {
  192. if (fq.id() == data.id()) {
  193. self.fqs.remove(fq);
  194. // Also re-init range select widget
  195. var rangeWidget = vm.collection.getFacetById(fq.id());
  196. if (data.dontZoomOut == undefined && rangeWidget != null && RANGE_SELECTABLE_WIDGETS.indexOf(rangeWidget.widgetType()) != -1 && fq.type() == 'range') {
  197. vm.collection.rangeZoomOut({'id': rangeWidget.id()});
  198. }
  199. found = true;
  200. return false;
  201. }
  202. });
  203. return found;
  204. };
  205. self.paginate = function (direction) {
  206. if (direction == 'next') {
  207. self.start(self.start() + vm.collection.template.rows() * 1.0);
  208. } else {
  209. self.start(self.start() - vm.collection.template.rows() * 1.0);
  210. }
  211. vm.search();
  212. };
  213. };
  214. var FieldAnalysis = function (vm, field_name) {
  215. var self = this;
  216. self.name = ko.observable(field_name);
  217. self.isLoading = ko.observable(true);
  218. self.section = ko.observable('terms');
  219. self.section.subscribe(function () {
  220. self.update();
  221. });
  222. self.terms = ko.mapping.fromJS({'prefix': '', 'data': []});
  223. self.terms.prefix.subscribe(function () {
  224. self.getTerms();
  225. });
  226. self.terms.prefix.extend({rateLimit: {timeout: 2000, method: "notifyWhenChangesStop"}});
  227. self.stats = ko.mapping.fromJS({'facet': '', 'data': []});
  228. var _statsUpdateTimeout = -1;
  229. self.stats.facet.subscribe(function () {
  230. // this is to avoid false positives from typeahead blur
  231. window.clearTimeout(_statsUpdateTimeout);
  232. _statsUpdateTimeout = window.setTimeout(function(){self.getStats()}, 200);
  233. });
  234. self.update = function() {
  235. if (self.section() == 'stats') {
  236. if (self.stats.data().length == 0) {
  237. self.getStats();
  238. }
  239. } else {
  240. if (self.terms.data().length == 0) {
  241. self.getTerms();
  242. }
  243. }
  244. }
  245. self.getTerms = function () {
  246. self.isLoading(true);
  247. self.terms.data.removeAll();
  248. $.post("/search/get_terms", {
  249. collection: ko.mapping.toJSON(vm.collection),
  250. analysis: ko.mapping.toJSON(self)
  251. }, function (data) {
  252. if (data.status == 0) {
  253. if (data.terms != null) {
  254. $.each(data.terms, function (key, val) {
  255. self.terms.data.push({'key': key, 'val': val});
  256. });
  257. }
  258. }
  259. else if (data.status == 1) {
  260. self.terms.data.push({'key': 'Error', 'val': data.message});
  261. }
  262. else {
  263. $(document).trigger("error", data.message);
  264. }
  265. self.isLoading(false);
  266. }).fail(function (xhr, textStatus, errorThrown) {
  267. $(document).trigger("error", xhr.responseText);
  268. });
  269. };
  270. self.getStats = function () {
  271. self.stats.data.removeAll();
  272. self.isLoading(true);
  273. $.post("/search/get_stats", {
  274. collection: ko.mapping.toJSON(vm.collection),
  275. query: ko.mapping.toJSON(vm.query),
  276. analysis: ko.mapping.toJSON(self)
  277. }, function (data) {
  278. if (data.status == 0) {
  279. if (data.stats.stats.stats_fields[self.name()] != null) {
  280. $.each(data.stats.stats.stats_fields[self.name()], function (key, val) {
  281. self.stats.data.push({'key': key, 'val': val});
  282. });
  283. }
  284. }
  285. else if (data.status == 1) {
  286. self.stats.data.push({'key': 'Error', 'val': data.message});
  287. }
  288. else {
  289. $(document).trigger("error", data.message);
  290. }
  291. self.isLoading(false);
  292. }).fail(function (xhr, textStatus, errorThrown) {
  293. $(document).trigger("error", xhr.responseText);
  294. });
  295. };
  296. }
  297. var Collection = function (vm, collection) {
  298. var self = this;
  299. self.id = collection.id;
  300. self.name = ko.mapping.fromJS(collection.name);
  301. self.label = ko.mapping.fromJS(collection.label);
  302. self.enabled = ko.mapping.fromJS(collection.enabled);
  303. self.idField = ko.observable(collection.idField);
  304. self.template = ko.mapping.fromJS(collection.template);
  305. self.template.fieldsSelected.subscribe(function () {
  306. vm.search();
  307. });
  308. self.template.extracode($("<span>").html(self.template.extracode()).text()); // Unescape HTML
  309. self.template.extracode.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  310. self.template.template.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  311. self.template.template.subscribe(function () {
  312. vm.search();
  313. });
  314. self.template.isGridLayout.subscribe(function () {
  315. vm.results.removeAll();
  316. vm.search();
  317. });
  318. if (self.template.leafletmap.latitudeField == undefined) {
  319. self.template.leafletmap.latitudeField = ko.observable();
  320. }
  321. if (self.template.leafletmap.longitudeField == undefined) {
  322. self.template.leafletmap.longitudeField = ko.observable();
  323. }
  324. if (self.template.leafletmap.labelField == undefined) {
  325. self.template.leafletmap.labelField = ko.observable();
  326. }
  327. self.template.leafletmapOn = ko.computed(function() {
  328. return self.template.leafletmap.latitudeField() != null && self.template.leafletmap.longitudeField() != null;
  329. });
  330. self.template.leafletmap.latitudeField.subscribe(function (newValue) {
  331. if (self.template.leafletmap.longitudeField() != null && newValue != null) {
  332. vm.search();
  333. }
  334. });
  335. self.template.leafletmap.longitudeField.subscribe(function (newValue) {
  336. if (self.template.leafletmap.latitudeField() != null && newValue != null) {
  337. vm.search();
  338. }
  339. });
  340. self.template.leafletmap.labelField.subscribe(function (newValue) {
  341. if (self.template.leafletmapOn()) {
  342. vm.search();
  343. }
  344. });
  345. self.template.selectedVisualField = ko.observable();
  346. self.template.selectedVisualFunction = ko.observable();
  347. self.template.selectedVisualFunction.subscribe(function (newValue) {
  348. var _vf = $("#visualFunctions");
  349. _vf.siblings(".muted").text(_vf.find(":selected").attr("title"));
  350. });
  351. self.template.selectedSourceField = ko.observable();
  352. self.template.selectedSourceFunction = ko.observable();
  353. self.template.selectedSourceFunction.subscribe(function (newValue) {
  354. var _sf = $("#sourceFunctions");
  355. _sf.siblings(".muted").text(_sf.find(":selected").attr("title"));
  356. });
  357. self.template.addFieldToVisual = function () {
  358. $(document).trigger("addFieldToVisual", self.template.selectedVisualField());
  359. };
  360. self.template.addFunctionToVisual = function () {
  361. $(document).trigger("addFunctionToVisual", self.template.selectedVisualFunction());
  362. };
  363. self.template.addFieldToSource = function () {
  364. $(document).trigger("addFieldToSource", self.template.selectedSourceField());
  365. };
  366. self.template.addFunctionToSource = function () {
  367. $(document).trigger("addFunctionToSource", self.template.selectedSourceFunction());
  368. };
  369. self.facets = ko.mapping.fromJS(collection.facets);
  370. $.each(self.facets(), function (index, facet) {
  371. facet.properties.limit.subscribe(function () {
  372. vm.search();
  373. });
  374. });
  375. self.template.rows.subscribe(function() {
  376. vm.search();
  377. });
  378. self.template.rows.extend({rateLimit: {timeout: 1500, method: "notifyWhenChangesStop"}});
  379. self.fields = ko.mapping.fromJS(collection.fields);
  380. self.availableFacetFields = ko.computed(function() {
  381. var facetFieldNames = $.map(self.facets(), function(facet) {
  382. return facet.field();
  383. });
  384. return $.grep(self.fields(), function(field) {
  385. return facetFieldNames.indexOf(field.name()) == -1;
  386. });
  387. });
  388. self.selectedDocument = ko.observable({});
  389. self.addFacet = function (facet_json) {
  390. self.removeFacet(function(){return facet_json.widget_id});
  391. logGA('add_facet/' + facet_json.widgetType);
  392. $.post("/search/template/new_facet", {
  393. "collection": ko.mapping.toJSON(self),
  394. "id": facet_json.widget_id,
  395. "label": facet_json.name,
  396. "field": facet_json.name,
  397. "widget_type": facet_json.widgetType
  398. }, function (data) {
  399. if (data.status == 0) {
  400. var facet = ko.mapping.fromJS(data.facet);
  401. facet.properties.limit.subscribe(function () {
  402. vm.search();
  403. });
  404. self.facets.push(facet);
  405. vm.search();
  406. } else {
  407. $(document).trigger("error", data.message);
  408. }
  409. }).fail(function (xhr, textStatus, errorThrown) {});
  410. };
  411. self.addPivotFacetValue = function(facet) {
  412. var pivot = null;
  413. if (typeof facet.properties.facets_form.field == 'string') { // Hackish but we load back properties as simple objects
  414. pivot = ko.mapping.fromJS({
  415. 'field': facet.properties.facets_form.field,
  416. 'limit': facet.properties.facets_form.limit,
  417. 'mincount': facet.properties.facets_form.mincount
  418. });
  419. facet.properties.facets_form.field = null;
  420. facet.properties.facets_form.limit = 5;
  421. facet.properties.facets_form.mincount = 1;
  422. } else {
  423. if (typeof facet.properties.facets_form.field != 'undefined') {
  424. pivot = ko.mapping.fromJS({
  425. 'field': facet.properties.facets_form.field(),
  426. 'limit': facet.properties.facets_form.limit(),
  427. 'mincount': facet.properties.facets_form.mincount()
  428. });
  429. facet.properties.facets_form.field(null);
  430. facet.properties.facets_form.limit(5);
  431. facet.properties.facets_form.mincount(1);
  432. }
  433. }
  434. if (pivot != null) {
  435. facet.properties.facets.push(pivot);
  436. vm.search();
  437. }
  438. }
  439. self.removePivotFacetValue = function(facet) {
  440. facet['pivot_facet'].properties.facets.remove(facet['value']);
  441. vm.search();
  442. }
  443. self.removeFacet = function (widget_id) {
  444. $.each(self.facets(), function (index, facet) {
  445. if (facet.id() == widget_id()) {
  446. self.facets.remove(facet);
  447. return false;
  448. }
  449. });
  450. }
  451. self.removeLeaflet = function (widget_json) {
  452. if (widget_json.widgetType() == "leafletmap-widget") {
  453. self.template.leafletmap.latitudeField(null);
  454. self.template.leafletmap.longitudeField(null);
  455. self.template.leafletmap.labelField(null);
  456. }
  457. }
  458. self.getFacetById = function (facet_id) {
  459. var _facet = null;
  460. $.each(self.facets(), function (index, facet) {
  461. if (facet.id() == facet_id) {
  462. _facet = facet;
  463. return false;
  464. }
  465. });
  466. return _facet;
  467. }
  468. self.getFacetByType = function (facetType) {
  469. var _facet = null;
  470. $.each(self.facets(), function (index, facet) {
  471. if (facet.widgetType() == facetType) {
  472. _facet = facet;
  473. return false;
  474. }
  475. });
  476. return _facet;
  477. }
  478. self.getHistogramFacet = function () { // Should do multi histogram
  479. return self.getFacetByType('histogram-widget');
  480. }
  481. self.template.fields = ko.computed(function () {
  482. var _fields = [];
  483. $.each(self.template.fieldsAttributes(), function (index, field) {
  484. var position = self.template.fieldsSelected.indexOf(field.name());
  485. if (position != -1) {
  486. _fields[position] = field;
  487. }
  488. });
  489. return _fields;
  490. });
  491. self.template.fieldsNames = ko.computed(function () {
  492. return $.map(self.template.fieldsAttributes(), function(field) {
  493. return field.name();
  494. });
  495. });
  496. self.getTemplateField = function (name) {
  497. var _field = null;
  498. $.each(self.template.fields(), function (index, field) {
  499. if (field.name() == name) {
  500. _field = field;
  501. return false;
  502. }
  503. });
  504. return _field;
  505. };
  506. self.template.fieldsModalFilter = ko.observable(""); // For UI
  507. self.template.fieldsModalType = ko.observable(""); // For UI
  508. self.template.fieldsAttributesFilter = ko.observable(""); // For UI
  509. self.template.filteredModalFields = ko.observableArray();
  510. self.template.filteredAttributeFieldsAll = ko.observable(true);
  511. self.template.filteredAttributeFields = ko.computed(function() {
  512. var _fields = [];
  513. var _iterable = self.template.fieldsAttributes();
  514. if (! self.template.filteredAttributeFieldsAll()){
  515. _iterable = self.template.fields();
  516. }
  517. $.each(_iterable, function (index, field) {
  518. if (self.template.fieldsAttributesFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsAttributesFilter().toLowerCase()) > -1){
  519. _fields.push(field);
  520. }
  521. });
  522. return _fields;
  523. });
  524. self.template.availableWidgetFields = ko.computed(function() {
  525. if (self.template.fieldsModalType() == 'histogram-widget') {
  526. return vm.availableDateFields();
  527. }
  528. else if (self.template.fieldsModalType() == 'line-widget') {
  529. return vm.availableNumberFields();
  530. }
  531. else if (self.template.fieldsModalType() == 'tree-widget' || self.template.fieldsModalType() == 'heatmap-widget') {
  532. return vm.availablePivotFields();
  533. }
  534. else {
  535. return self.availableFacetFields();
  536. }
  537. });
  538. self.template.availableWidgetFieldsNames = ko.computed(function() {
  539. return $.map(self.template.availableWidgetFields(), function(field) {
  540. return field.name();
  541. });
  542. });
  543. self.template.fieldsModalFilter.subscribe(function(value) {
  544. var _fields = [];
  545. var _availableFields = self.template.availableWidgetFields();
  546. $.each(_availableFields, function (index, field) {
  547. if (self.template.fieldsModalFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  548. _fields.push(field);
  549. }
  550. });
  551. self.template.filteredModalFields(_fields);
  552. });
  553. self.switchCollection = function() { // Long term would be to reload the page
  554. $.post("/search/get_collection", {
  555. name: self.name()
  556. }, function (data) {
  557. if (data.status == 0) {
  558. self.idField(data.collection.collection.idField);
  559. self.template.template(data.collection.collection.template.template);
  560. self.template.fieldsAttributes.removeAll();
  561. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  562. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  563. });
  564. self.fields.removeAll();
  565. $.each(data.collection.collection.fields, function(index, field) {
  566. self.fields.push(ko.mapping.fromJS(field));
  567. });
  568. }
  569. }).fail(function (xhr, textStatus, errorThrown) {});
  570. };
  571. function diff(A, B) {
  572. return A.filter(function (a) {
  573. return B.indexOf(a) == -1;
  574. });
  575. }
  576. function syncArray(currentObservable, newJson, isDynamic) {
  577. // Get names of fields
  578. var _currentFieldsNames = $.map(
  579. $.grep(currentObservable(), function(field) {
  580. return field.isDynamic() == isDynamic;
  581. }), function(field) {
  582. return field.name();
  583. });
  584. var _newFieldsNames = $.map(
  585. $.grep(newJson, function(field) {
  586. return field.isDynamic == isDynamic;
  587. }), function(field) {
  588. return field.name;
  589. });
  590. var _toDelete = diff(_currentFieldsNames, _newFieldsNames);
  591. var _toAdd = diff(_newFieldsNames, _currentFieldsNames);
  592. // Deleted fields
  593. self.template.fieldsSelected.removeAll(_toDelete);
  594. var bulk = $.grep(currentObservable(), function(field) {
  595. return (_toDelete.indexOf(field.name()) != -1)
  596. });
  597. currentObservable.removeAll(bulk);
  598. // New fields
  599. $.each(newJson, function(index, field) {
  600. if (_toAdd.indexOf(field.name) != -1) {
  601. currentObservable.push(ko.mapping.fromJS(field));
  602. }
  603. });
  604. }
  605. self.syncFields = function() {
  606. $.post("/search/get_collection", {
  607. name: self.name()
  608. }, function (data) {
  609. if (data.status == 0) {
  610. self.idField(data.collection.collection.idField);
  611. syncArray(self.template.fieldsAttributes, data.collection.collection.template.fieldsAttributes, false);
  612. syncArray(self.fields, data.collection.collection.fields, false);
  613. }
  614. // After sync the dynamic fields
  615. self.syncDynamicFields()
  616. }).fail(function (xhr, textStatus, errorThrown) {});
  617. };
  618. self.syncDynamicFields = function () {
  619. $.post("/search/index/fields/dynamic", {
  620. name: self.name()
  621. }, function (data) {
  622. if (data.status == 0) {
  623. syncArray(self.template.fieldsAttributes, data.gridlayout_header_fields, true);
  624. syncArray(self.fields, data.fields, true);
  625. }
  626. }).fail(function (xhr, textStatus, errorThrown) {});
  627. };
  628. self.toggleSortColumnGridLayout = function (template_field) {
  629. if (! template_field.sort.direction()) {
  630. template_field.sort.direction('desc');
  631. } else if (template_field.sort.direction() == 'desc') {
  632. template_field.sort.direction('asc');
  633. } else {
  634. template_field.sort.direction(null);
  635. }
  636. $(document).trigger("setResultsHeight");
  637. vm.search();
  638. };
  639. self.toggleSortFacet = function (facet_field, event) {
  640. if (facet_field.properties.sort() == 'desc') {
  641. facet_field.properties.sort('asc');
  642. } else {
  643. facet_field.properties.sort('desc');
  644. }
  645. $(event.target).button('loading');
  646. vm.search();
  647. };
  648. self.toggleRangeFacet = function (facet_field, event) {
  649. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  650. if (facet_field.type() == 'field') {
  651. facet_field.type('range');
  652. } else if (facet_field.type() == 'range') {
  653. facet_field.type('field')
  654. }
  655. $(event.target).button('loading');
  656. vm.search();
  657. };
  658. self.selectTimelineFacet = function (data) {
  659. var facet = self.getFacetById(data.widget_id);
  660. facet.properties.start(data.from);
  661. facet.properties.end(data.to);
  662. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  663. $.ajax({
  664. type: "POST",
  665. url: "/search/get_range_facet",
  666. data: {
  667. collection: ko.mapping.toJSON(self),
  668. facet: ko.mapping.toJSON(facet),
  669. action: 'select'
  670. },
  671. success: function (data) {
  672. if (data.status == 0) {
  673. facet.properties.gap(data.properties.gap);
  674. }
  675. },
  676. async: false
  677. });
  678. vm.search();
  679. }
  680. self.rangeZoomOut = function (facet_json) {
  681. var facet = self.getFacetById(typeof facet_json.id == "function" ? facet_json.id() : facet_json.id);
  682. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_json.id}));
  683. if (facet.properties.gap() != null) { // Bar, line charts don't have gap
  684. facet.properties.gap(facet.properties.initial_gap());
  685. }
  686. if (facet.properties.initial_start() != null) { // Bar and line charts
  687. facet.properties.start(facet.properties.initial_start());
  688. facet.properties.end(facet.properties.initial_end());
  689. }
  690. vm.search();
  691. }
  692. self.translateSelectedField = function (index, direction) {
  693. var array = self.template.fieldsSelected();
  694. if (direction == 'left') {
  695. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  696. } else {
  697. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  698. }
  699. };
  700. self.upDownFacetLimit = function (facet_id, direction) {
  701. var facet = self.getFacetById(facet_id);
  702. if (facet.properties.prevLimit == undefined) {
  703. facet.properties.prevLimit = facet.properties.limit();
  704. }
  705. if (direction == 'up') {
  706. facet.properties.limit(facet.properties.limit() + 10);
  707. } else {
  708. facet.properties.limit(facet.properties.limit() - 10);
  709. }
  710. vm.search();
  711. };
  712. };
  713. var NewTemplate = function (vm, initial) {
  714. var self = this;
  715. self.collections = ko.mapping.fromJS(initial.collections);
  716. self.layout = initial.layout;
  717. self.inited = ko.observable(self.collections().length > 0); // No collection if not a new dashboard
  718. self.init = function() {
  719. if (self.inited()) {
  720. // If new dashboard
  721. vm.collection.name.subscribe(function(newValue) {
  722. vm.collection.label(newValue);
  723. vm.collection.switchCollection();
  724. vm.search();
  725. });
  726. } else {
  727. self.syncCollections();
  728. }
  729. if (initial.autoLoad) {
  730. magicLayout(vm);
  731. }
  732. };
  733. self.syncCollections = function () {
  734. $.post("/search/get_collections", {
  735. collection: ko.mapping.toJSON(vm.collection),
  736. }, function (data) {
  737. if (data.status == 0) {
  738. // Sync new and old names
  739. $.each(data.collection, function(index, name) {
  740. if (self.collections.indexOf(name) == -1) {
  741. self.collections.push(name);
  742. }
  743. });
  744. $.each(self.collections(), function(index, collection) {
  745. if (data.collection.indexOf(collection) == -1) {
  746. self.collections.remove(collection);
  747. }
  748. });
  749. }
  750. else {
  751. $(document).trigger("error", data.message);
  752. }
  753. }).fail(function (xhr, textStatus, errorThrown) {
  754. $(document).trigger("error", xhr.responseText);
  755. }).done(function() {
  756. self.inited(true);
  757. });
  758. };
  759. };
  760. var DATE_TYPES = ['date', 'tdate'];
  761. var NUMBER_TYPES = ['int', 'tint', 'long', 'tlong', 'float', 'tfloat', 'double', 'tdouble'];
  762. var RANGE_SELECTABLE_WIDGETS = ['histogram-widget', 'bar-widget', 'line-widget'];
  763. var SearchViewModel = function (collection_json, query_json, initial_json) {
  764. var self = this;
  765. self.intervalOptions = ko.observableArray(ko.bindingHandlers.daterangepicker.INTERVAL_OPTIONS);
  766. // Models
  767. self.collection = new Collection(self, collection_json.collection);
  768. self.query = new Query(self, query_json);
  769. self.initial = new NewTemplate(self, initial_json);
  770. // UI
  771. self.response = ko.observable({});
  772. self.results = ko.observableArray([]);
  773. self.norm_facets = ko.computed(function () {
  774. return self.response().normalized_facets;
  775. });
  776. self.getFacetFromQuery = function (facet_id) {
  777. var _facet = null;
  778. if (self.norm_facets() !== undefined) {
  779. $.each(self.norm_facets(), function (index, norm_facet) {
  780. if (norm_facet.id == facet_id) {
  781. _facet = norm_facet;
  782. }
  783. });
  784. }
  785. return _facet;
  786. };
  787. self.toggledGridlayoutResultChevron = ko.observable(false);
  788. self.enableGridlayoutResultChevron = function() {
  789. self.toggledGridlayoutResultChevron(true);
  790. };
  791. self.disableGridlayoutResultChevron = function() {
  792. self.toggledGridlayoutResultChevron(false);
  793. };
  794. self.fieldAnalyses = ko.observableArray([]);
  795. self.fieldAnalysesName = ko.observableArray("");
  796. self.fieldsAnalysisAttributesNames = ko.computed(function () {
  797. var _fields = [];
  798. $.each(self.collection.template.fieldsAttributes(), function (index, field) {
  799. if (field.name() != self.fieldAnalysesName()){
  800. _fields.push(field.name())
  801. }
  802. });
  803. return _fields;
  804. });
  805. self.previewColumns = ko.observable("");
  806. self.columns = ko.observable([]);
  807. loadLayout(self, collection_json.layout);
  808. self.isEditing = ko.observable(false);
  809. self.toggleEditing = function () {
  810. self.isEditing(! self.isEditing());
  811. };
  812. self.isRetrievingResults = ko.observable(false);
  813. function bareWidgetBuilder(name, type){
  814. return new Widget({
  815. size: 12,
  816. id: UUID(),
  817. name: name,
  818. widgetType: type
  819. });
  820. }
  821. self.draggableHit = ko.observable(bareWidgetBuilder("Hit Count", "hit-widget"));
  822. self.draggableFacet = ko.observable(bareWidgetBuilder("Facet", "facet-widget"));
  823. self.draggableResultset = ko.observable(bareWidgetBuilder("Grid Results", "resultset-widget"));
  824. self.draggableHtmlResultset = ko.observable(bareWidgetBuilder("HTML Results", "html-resultset-widget"));
  825. self.draggableHistogram = ko.observable(bareWidgetBuilder("Histogram", "histogram-widget"));
  826. self.draggableBar = ko.observable(bareWidgetBuilder("Bar Chart", "bar-widget"));
  827. self.draggableMap = ko.observable(bareWidgetBuilder("Map", "map-widget"));
  828. self.draggableLeafletMap = ko.observable(bareWidgetBuilder("Marker Map", "leafletmap-widget"));
  829. self.draggableLine = ko.observable(bareWidgetBuilder("Line Chart", "line-widget"));
  830. self.draggablePie = ko.observable(bareWidgetBuilder("Pie Chart", "pie-widget"));
  831. self.draggableFilter = ko.observable(bareWidgetBuilder("Filter Bar", "filter-widget"));
  832. self.draggableTree = ko.observable(bareWidgetBuilder("Tree", "tree-widget"));
  833. self.draggableHeatmap = ko.observable(bareWidgetBuilder("Heatmap", "heatmap-widget"));
  834. self.availableDateFields = ko.computed(function() {
  835. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPES.indexOf(field.type()) != -1; });
  836. });
  837. self.availableNumberFields = ko.computed(function() {
  838. return $.grep(self.collection.availableFacetFields(), function(field) { return NUMBER_TYPES.indexOf(field.type()) != -1; });
  839. });
  840. self.availablePivotFields = ko.computed(function() {
  841. return self.collection.fields();
  842. });
  843. function getWidgets(equalsTo) {
  844. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  845. };
  846. self.availableDraggableResultset = ko.computed(function() {
  847. return getWidgets(function(widget) { return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  848. });
  849. self.availableDraggableLeaflet = ko.computed(function() {
  850. return getWidgets(function(widget) { return ['leafletmap-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  851. });
  852. self.availableDraggableFilter = ko.computed(function() {
  853. return getWidgets(function(widget) { return widget.widgetType() == 'filter-widget'; }).length == 0;
  854. });
  855. self.availableDraggableHistogram = ko.computed(function() {
  856. return getWidgets(function(widget) { return widget.widgetType() == 'histogram-widget'; }).length == 0 && self.availableDateFields().length > 0;
  857. });
  858. self.availableDraggableNumbers = ko.computed(function() {
  859. return self.availableNumberFields().length > 0;
  860. });
  861. self.availableDraggableChart = ko.computed(function() {
  862. return self.collection.availableFacetFields().length > 0;
  863. });
  864. self.init = function (callback) {
  865. self.initial.init();
  866. self.collection.syncFields();
  867. self.search(callback);
  868. }
  869. self.searchBtn = function () {
  870. self.query.start(0);
  871. self.search();
  872. };
  873. self.search = function (callback) {
  874. self.isRetrievingResults(true);
  875. $(".jHueNotify").hide();
  876. logGA('search');
  877. // Multi queries
  878. var multiQs = [];
  879. var multiQ = self.query.getMultiq();
  880. if (multiQ != null) {
  881. var facet = {};
  882. var queries = [];
  883. if (multiQ == 'query') {
  884. queries = self.query.qs();
  885. } else {
  886. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  887. queries = $.map(facet.filter(), function(f) { return f.value(); });
  888. }
  889. multiQs = $.map(queries, function(qdata) {
  890. return $.post("/search/get_timeline", {
  891. collection: ko.mapping.toJSON(self.collection),
  892. query: ko.mapping.toJSON(self.query),
  893. facet: ko.mapping.toJSON(facet),
  894. qdata: ko.mapping.toJSON(qdata),
  895. multiQ: multiQ
  896. }, function (data) {return data});
  897. });
  898. }
  899. $.each(self.fieldAnalyses(), function (index, analyse) { // Invalidate stats analysis
  900. analyse.stats.data.removeAll();
  901. });
  902. if (self.getFieldAnalysis()) {
  903. self.getFieldAnalysis().update();
  904. }
  905. $.when.apply($, [
  906. $.post("/search/search", {
  907. collection: ko.mapping.toJSON(self.collection),
  908. query: ko.mapping.toJSON(self.query),
  909. layout: ko.mapping.toJSON(self.columns)
  910. }, function (data) {
  911. if (typeof callback != undefined && callback != null){
  912. callback(data);
  913. }
  914. self.response(data);
  915. self.results.removeAll();
  916. if (data.error) {
  917. $(document).trigger("error", data.error);
  918. }
  919. else {
  920. if (self.collection.template.isGridLayout()) {
  921. // Table view
  922. var _docs = [];
  923. var leafletmap = {};
  924. $.each(data.response.docs, function (index, item) {
  925. var row = [];
  926. var _showDetails = item.showDetails;
  927. var _details = item.details;
  928. delete item["showDetails"];
  929. delete item["details"];
  930. var fields = self.collection.template.fieldsSelected();
  931. // Display selected fields or whole json document
  932. if (fields.length != 0) {
  933. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  934. row.push(item[field]);
  935. });
  936. } else {
  937. row.push(ko.mapping.toJSON(item));
  938. }
  939. if (self.collection.template.leafletmapOn()) {
  940. leafletmap = {
  941. 'latitude': item[self.collection.template.leafletmap.latitudeField()],
  942. 'longitude': item[self.collection.template.leafletmap.longitudeField()],
  943. 'label': self.collection.template.leafletmap.labelField() ? item[self.collection.template.leafletmap.labelField()] : ""
  944. }
  945. }
  946. var doc = {
  947. 'id': item[self.collection.idField()],
  948. 'row': row,
  949. 'showDetails': ko.observable(_showDetails),
  950. 'details': ko.observableArray(_details),
  951. 'leafletmap': leafletmap
  952. };
  953. _docs.push(doc);
  954. });
  955. self.results(_docs);
  956. }
  957. else {
  958. // Template view
  959. var _docs = [];
  960. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  961. $.each(data.response.docs, function (index, item) {
  962. // fix the fields that contain dots in the name
  963. addTemplateFunctions(item);
  964. _docs.push(Mustache.render(_mustacheTmpl, item));
  965. });
  966. self.results(_docs);
  967. }
  968. self.isRetrievingResults(false);
  969. }
  970. })
  971. ].concat(multiQs)
  972. )
  973. .done(function() {
  974. if (arguments[0] instanceof Array) { // If multi queries
  975. var histoFacetId = self.collection.getHistogramFacet().id();
  976. var histoFacet = self.getFacetFromQuery(histoFacetId);
  977. for (var i = 1; i < arguments.length; i++) {
  978. histoFacet.extraSeries.push(arguments[i][0]['series']);
  979. }
  980. self.response.valueHasMutated();
  981. }
  982. })
  983. .fail(function (xhr, textStatus, errorThrown) {
  984. $(document).trigger("error", xhr.responseText);
  985. })
  986. .always(function () {
  987. $('.btn-loading').button('reset');
  988. });
  989. };
  990. self.removeWidget = function (widget_json) {
  991. self.collection.removeFacet(widget_json.id);
  992. self.collection.removeLeaflet(widget_json);
  993. var refresh = self.query.removeFilter(widget_json);
  994. self.removeWidgetById(widget_json.id());
  995. if (refresh) {
  996. self.search();
  997. }
  998. }
  999. self.getWidgetById = function (widget_id) {
  1000. var _widget = null;
  1001. $.each(self.columns(), function (i, col) {
  1002. $.each(col.rows(), function (j, row) {
  1003. $.each(row.widgets(), function (z, widget) {
  1004. if (widget.id() == widget_id){
  1005. _widget = widget;
  1006. return false;
  1007. }
  1008. });
  1009. });
  1010. });
  1011. return _widget;
  1012. }
  1013. self.removeWidgetById = function (widget_id) {
  1014. $.each(self.columns(), function (i, col) {
  1015. $.each(col.rows(), function (j, row) {
  1016. $.each(row.widgets(), function (z, widget) {
  1017. if (widget && widget.id() == widget_id){
  1018. row.widgets.remove(widget);
  1019. row.autosizeWidgets();
  1020. return false;
  1021. }
  1022. });
  1023. });
  1024. });
  1025. }
  1026. self.getDocument = function (doc) {
  1027. $.post("/search/get_document", {
  1028. collection: ko.mapping.toJSON(self.collection),
  1029. id: doc.id
  1030. }, function (data) {
  1031. if (data.status == 0) {
  1032. $.each(data.doc.doc, function(key, val) {
  1033. doc['details'].push(ko.mapping.fromJS({
  1034. key: key,
  1035. value: val
  1036. }));
  1037. });
  1038. }
  1039. else if (data.status == 1) {
  1040. $(document).trigger("info", data.message);
  1041. doc['details'].push(ko.mapping.fromJS({
  1042. key: '',
  1043. value: ''
  1044. }));
  1045. }
  1046. else {
  1047. $(document).trigger("error", data.message);
  1048. }
  1049. }).fail(function (xhr, textStatus, errorThrown) {
  1050. $(document).trigger("error", xhr.responseText);
  1051. });
  1052. };
  1053. self.showFieldAnalysis = function() {
  1054. if (self.fieldAnalysesName()) {
  1055. var analyse = self.getFieldAnalysis();
  1056. if (analyse == null) {
  1057. analyse = new FieldAnalysis(self, self.fieldAnalysesName());
  1058. self.fieldAnalyses.push(analyse);
  1059. }
  1060. analyse.update();
  1061. $(document).trigger("shownAnalysis")
  1062. }
  1063. }
  1064. self.getFieldAnalysis = function() {
  1065. var field_name = self.fieldAnalysesName();
  1066. var _analyse = null;
  1067. $.each(self.fieldAnalyses(), function (index, analyse) {
  1068. if (analyse.name() == field_name) {
  1069. _analyse = analyse;
  1070. return false;
  1071. }
  1072. });
  1073. return _analyse;
  1074. }
  1075. self.save = function () {
  1076. $.post("/search/save", {
  1077. collection: ko.mapping.toJSON(self.collection),
  1078. layout: ko.mapping.toJSON(self.columns)
  1079. }, function (data) {
  1080. if (data.status == 0) {
  1081. self.collection.id = data.id;
  1082. $(document).trigger("info", data.message);
  1083. if (window.location.search.indexOf("collection") == -1) {
  1084. window.location.hash = '#collection=' + data.id;
  1085. }
  1086. }
  1087. else {
  1088. $(document).trigger("error", data.message);
  1089. }
  1090. }).fail(function (xhr, textStatus, errorThrown) {
  1091. $(document).trigger("error", xhr.responseText);
  1092. });
  1093. };
  1094. };
  1095. function logGA(page) {
  1096. if (typeof trackOnGA == 'function') {
  1097. trackOnGA('search/' + page);
  1098. }
  1099. }