search.ko.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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. // Start dashboard lib to move out
  17. var Column = function (size, rows) {
  18. var self = this;
  19. self.size = ko.observable(size);
  20. self.rows = ko.observableArray(rows);
  21. self.drops = ko.observableArray(["temp"]);
  22. self.klass = ko.computed(function () {
  23. return "card card-home card-column span" + self.size();
  24. });
  25. self.addEmptyRow = function (atBeginning) {
  26. return self.addRow(null, atBeginning);
  27. };
  28. self.addRow = function (row, atBeginning) {
  29. if (typeof row == "undefined" || row == null) {
  30. row = new Row([]);
  31. }
  32. if (typeof atBeginning == "undefined" || atBeginning == null) {
  33. self.rows.push(row);
  34. }
  35. else {
  36. self.rows.unshift(row);
  37. }
  38. return row;
  39. };
  40. }
  41. var Row = function (widgets) {
  42. var self = this;
  43. self.widgets = ko.observableArray(widgets);
  44. self.addWidget = function (widget) {
  45. self.widgets.push(widget);
  46. };
  47. self.move = function (from, to) {
  48. try {
  49. viewModel.columns()[to].addRow(self);
  50. viewModel.columns()[from].rows.remove(self);
  51. }
  52. catch (exception) {
  53. }
  54. }
  55. self.moveDown = function (col, row) {
  56. var _i = col.rows().indexOf(row);
  57. if (_i < col.rows().length - 1) {
  58. var _arr = col.rows();
  59. col.rows.splice(_i, 2, _arr[_i + 1], _arr[_i]);
  60. }
  61. }
  62. self.moveUp = function (col, row) {
  63. var _i = col.rows().indexOf(row);
  64. if (_i >= 1) {
  65. var _arr = col.rows();
  66. col.rows.splice(_i - 1, 2, _arr[_i], _arr[_i - 1]);
  67. }
  68. }
  69. self.remove = function (col, row) {
  70. $.each(self.widgets(), function(i, widget) {
  71. viewModel.removeWidget(widget);
  72. });
  73. col.rows.remove(row);
  74. }
  75. }
  76. // A widget is generic. It has an id that refer to another object (e.g. facet) with the same id.
  77. var Widget = function (size, id, name, widgetType, properties, offset, loading) {
  78. var self = this;
  79. self.size = ko.observable(size).extend({ numeric: 0 });
  80. self.name = ko.observable(name);
  81. self.id = ko.observable(id);
  82. self.widgetType = ko.observable(typeof widgetType != "undefined" && widgetType != null ? widgetType : "empty-widget");
  83. self.properties = ko.observable(typeof properties != "undefined" && properties != null ? properties : {});
  84. self.offset = ko.observable(typeof offset != "undefined" && offset != null ? offset : 0).extend({ numeric: 0 });
  85. self.isLoading = ko.observable(typeof loading != "undefined" && loading != null ? loading : false);
  86. self.klass = ko.computed(function () {
  87. return "card card-widget span" + self.size() + (self.offset() * 1 > 0 ? " offset" + self.offset() : "");
  88. });
  89. self.expand = function () {
  90. self.size(self.size() + 1);
  91. $("#wdg_" + self.id()).trigger("resize");
  92. }
  93. self.compress = function () {
  94. self.size(self.size() - 1);
  95. $("#wdg_" + self.id()).trigger("resize");
  96. }
  97. self.moveLeft = function () {
  98. self.offset(self.offset() - 1);
  99. }
  100. self.moveRight = function () {
  101. self.offset(self.offset() + 1);
  102. }
  103. self.remove = function (row, widget) {
  104. viewModel.removeWidget(widget);
  105. row.widgets.remove(widget);
  106. }
  107. };
  108. Widget.prototype.clone = function () {
  109. return new Widget(this.size(), UUID(), this.name(), this.widgetType());
  110. };
  111. function fullLayout() {
  112. setLayout([12]);
  113. }
  114. function oneThirdLeftLayout() {
  115. setLayout([2, 10]);
  116. }
  117. function magicLayout(vm) {
  118. loadLayout(vm, vm.initial.layout);
  119. }
  120. function setLayout(colSizes) {
  121. // Save previous widgets
  122. var _allRows = [];
  123. $(viewModel.columns()).each(function (cnt, col) {
  124. var _tRows = [];
  125. $(col.rows()).each(function (icnt, row) {
  126. if (row.widgets().length > 0) {
  127. _tRows.push(row);
  128. }
  129. });
  130. _allRows = _allRows.concat(_tRows);
  131. });
  132. var _cols = [];
  133. var _highestCol = {
  134. idx: -1,
  135. size: -1
  136. };
  137. $(colSizes).each(function (cnt, size) {
  138. _cols.push(new Column(size, []));
  139. if (size > _highestCol.size) {
  140. _highestCol.idx = cnt;
  141. _highestCol.size = size;
  142. }
  143. });
  144. if (_allRows.length > 0 && _highestCol.idx > -1) {
  145. _cols[_highestCol.idx].rows(_allRows);
  146. }
  147. $(_cols).each(function (cnt, col) {
  148. if (col.rows().length == 0) {
  149. col.rows([new Row([])]);
  150. }
  151. });
  152. viewModel.columns(_cols);
  153. }
  154. function loadLayout(viewModel, json_layout) {
  155. var _columns = [];
  156. $(json_layout).each(function (cnt, json_col) {
  157. var _rows = [];
  158. $(json_col.rows).each(function (rcnt, json_row) {
  159. var row = new Row();
  160. $(json_row.widgets).each(function (wcnt, widget) {
  161. row.addWidget(new Widget(widget.size, widget.id, widget.name, widget.widgetType, widget.properties, widget.offset, true));
  162. });
  163. _rows.push(row);
  164. });
  165. var column = new Column(json_col.size, _rows);
  166. _columns = _columns.concat(column);
  167. });
  168. viewModel.columns(_columns);
  169. }
  170. // End dashboard lib
  171. var Query = function (vm, query) {
  172. var self = this;
  173. self.qs = ko.mapping.fromJS(query.qs);
  174. self.fqs = ko.mapping.fromJS(query.fqs);
  175. self.start = ko.mapping.fromJS(query.start);
  176. var defaultMultiqGroup = {'id': 'query', 'label': 'query'};
  177. self.multiqs = ko.computed(function () { // List of widgets supporting multiqs
  178. var histogram_id = vm.collection.getHistogramFacet();
  179. return [defaultMultiqGroup].concat(
  180. $.map($.grep(self.fqs(), function(fq, i) {
  181. return (fq.type() == 'field' || fq.type() == 'range') && (histogram_id == null || histogram_id.id() != fq.id());
  182. }), function(fq) { return {'id': fq.id(), 'label': fq.field()} })
  183. );
  184. });
  185. self.selectedMultiq = ko.observable(defaultMultiqGroup);
  186. self.getFacetFilter = function(widget_id) {
  187. var _fq = null;
  188. $.each(self.fqs(), function (index, fq) {
  189. if (fq.id() == widget_id) {
  190. _fq = fq;
  191. return false;
  192. }
  193. });
  194. return _fq;
  195. };
  196. self.getMultiq = ko.computed(function () {
  197. if (self.selectedMultiq()) {
  198. if (self.selectedMultiq() == 'query') {
  199. if (self.qs().length >= 2) {
  200. return 'query';
  201. }
  202. } else {
  203. var facet = self.getFacetFilter(self.selectedMultiq());
  204. if (facet && facet.filter().length > 0) {
  205. return 'facet';
  206. }
  207. }
  208. }
  209. return null;
  210. });
  211. self.selectedMultiq.subscribe(function () { // To keep below the computed
  212. vm.search();
  213. });
  214. self.addQ = function (data) {
  215. self.qs.push(ko.mapping.fromJS({'q': ''}));
  216. };
  217. self.removeQ = function (query) {
  218. self.qs.remove(query);
  219. };
  220. self.toggleFacet = function (data) {
  221. var fq = self.getFacetFilter(data.widget_id);
  222. if (fq == null) {
  223. self.fqs.push(ko.mapping.fromJS({
  224. 'id': data.widget_id,
  225. 'field': data.facet.cat,
  226. 'filter': [data.facet.value],
  227. 'type': 'field'
  228. }));
  229. } else {
  230. $.each(self.fqs(), function (index, fq) {
  231. if (fq.id() == data.widget_id) {
  232. if (fq.filter.indexOf(data.facet.value) > -1) {
  233. fq.filter.remove(data.facet.value);
  234. if (fq.filter().length == 0) {
  235. self.fqs.remove(fq);
  236. }
  237. } else {
  238. fq.filter.push(data.facet.value);
  239. }
  240. }
  241. });
  242. }
  243. vm.search();
  244. }
  245. self.selectRangeFacet = function (data) {
  246. if (data.force != undefined) {
  247. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  248. }
  249. var fq = self.getFacetFilter(data.widget_id);
  250. if (fq == null) {
  251. self.fqs.push(ko.mapping.fromJS({
  252. 'id': data.widget_id,
  253. 'field': data.cat,
  254. 'filter': [data.from],
  255. 'properties': [{'from': data.from, 'to': data.to}],
  256. 'type': 'range'
  257. }));
  258. } else {
  259. if (fq.filter().indexOf(data.from) > -1) { // Unselect
  260. fq.filter.remove(data.from);
  261. $.each(fq.properties(), function (index, prop) {
  262. if (prop && prop.from() == data.from) {
  263. fq.properties.remove(prop);
  264. }
  265. });
  266. if (fq.filter().length == 0) {
  267. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  268. }
  269. } else {
  270. fq.filter.push(data.from);
  271. fq.properties.push(ko.mapping.fromJS({'from': data.from, 'to': data.to}));
  272. }
  273. }
  274. if (data.no_refresh == undefined) {
  275. vm.search();
  276. }
  277. };
  278. self.removeFilter = function (data) {
  279. $.each(self.fqs(), function (index, fq) {
  280. if (fq.id() == data.id()) {
  281. self.fqs.remove(fq);
  282. // Also re-init range select widget
  283. var rangeWidget = vm.collection.getFacetById(fq.id());
  284. if (rangeWidget != null && RANGE_SELECTABLE_WIDGETS.indexOf(rangeWidget.widgetType()) != -1 && fq.type() == 'range') {
  285. vm.collection.timeLineZoom({'id': rangeWidget.id()});
  286. }
  287. return false;
  288. }
  289. });
  290. };
  291. self.paginate = function (direction) {
  292. if (direction == 'next') {
  293. self.start(self.start() + vm.collection.template.rows() * 1.0);
  294. } else {
  295. self.start(self.start() - vm.collection.template.rows() * 1.0);
  296. }
  297. vm.search();
  298. };
  299. };
  300. var Collection = function (vm, collection) {
  301. var self = this;
  302. self.id = collection.id;
  303. self.name = ko.mapping.fromJS(collection.name);
  304. self.label = ko.mapping.fromJS(collection.label);
  305. self.enabled = ko.mapping.fromJS(collection.enabled);
  306. self.idField = ko.observable(collection.idField);
  307. self.template = ko.mapping.fromJS(collection.template);
  308. self.template.fieldsSelected.subscribe(function () {
  309. vm.search();
  310. });
  311. self.template.extracode($("<span>").html(self.template.extracode()).text()); // Unescape HTML
  312. self.template.extracode.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  313. self.template.template.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  314. self.template.template.subscribe(function () {
  315. vm.search();
  316. });
  317. self.template.isGridLayout.subscribe(function () {
  318. vm.search();
  319. });
  320. self.template.selectedVisualField = ko.observable();
  321. self.template.selectedVisualFunction = ko.observable();
  322. self.template.selectedVisualFunction.subscribe(function (newValue) {
  323. var _vf = $("#visualFunctions");
  324. _vf.siblings(".muted").text(_vf.find(":selected").attr("title"));
  325. });
  326. self.template.selectedSourceField = ko.observable();
  327. self.template.selectedSourceFunction = ko.observable();
  328. self.template.selectedSourceFunction.subscribe(function (newValue) {
  329. var _sf = $("#sourceFunctions");
  330. _sf.siblings(".muted").text(_sf.find(":selected").attr("title"));
  331. });
  332. self.template.addFieldToVisual = function () {
  333. $(document).trigger("addFieldToVisual", self.template.selectedVisualField());
  334. };
  335. self.template.addFunctionToVisual = function () {
  336. $(document).trigger("addFunctionToVisual", self.template.selectedVisualFunction());
  337. };
  338. self.template.addFieldToSource = function () {
  339. $(document).trigger("addFieldToSource", self.template.selectedSourceField());
  340. };
  341. self.template.addFunctionToSource = function () {
  342. $(document).trigger("addFunctionToSource", self.template.selectedSourceFunction());
  343. };
  344. self.facets = ko.mapping.fromJS(collection.facets);
  345. $.each(self.facets(), function (index, facet) {
  346. facet.field.subscribe(function () {
  347. vm.search();
  348. });
  349. });
  350. self.template.rows.subscribe(function(){
  351. vm.search();
  352. });
  353. self.template.rows.extend({rateLimit: {timeout: 1500, method: "notifyWhenChangesStop"}});
  354. self.fields = ko.mapping.fromJS(collection.fields);
  355. self.availableFacetFields = ko.computed(function() {
  356. var facetFieldNames = $.map(self.facets(), function(facet) {
  357. return facet.field(); //filter out text_general, __version__
  358. });
  359. return $.grep(self.fields(), function(field) {
  360. return facetFieldNames.indexOf(field.name()) == -1;
  361. });
  362. });
  363. self.selectedDocument = ko.observable({});
  364. self.addFacet = function (facet_json) {
  365. self.removeFacet(function(){return facet_json.widget_id});
  366. $.post("/search/template/new_facet", {
  367. "collection": ko.mapping.toJSON(self),
  368. "id": facet_json.widget_id,
  369. "label": facet_json.name,
  370. "field": facet_json.name,
  371. "widget_type": facet_json.widgetType
  372. }, function (data) {
  373. if (data.status == 0) {
  374. var facet = ko.mapping.fromJS(data.facet);
  375. facet.field.subscribe(function () {
  376. vm.search();
  377. });
  378. self.facets.push(facet);
  379. vm.search();
  380. } else {
  381. $(document).trigger("error", data.message);
  382. }
  383. }).fail(function (xhr, textStatus, errorThrown) {});
  384. };
  385. self.removeFacet = function (widget_id) {
  386. $.each(self.facets(), function (index, facet) {
  387. if (facet.id() == widget_id()) {
  388. self.facets.remove(facet);
  389. return false;
  390. }
  391. });
  392. }
  393. self.getFacetById = function (facet_id) {
  394. var _facet = null;
  395. $.each(self.facets(), function (index, facet) {
  396. if (facet.id() == facet_id) {
  397. _facet = facet;
  398. return false;
  399. }
  400. });
  401. return _facet;
  402. }
  403. self.getFacetByType = function (facetType) {
  404. var _facet = null;
  405. $.each(self.facets(), function (index, facet) {
  406. if (facet.widgetType() == facetType) {
  407. _facet = facet;
  408. return false;
  409. }
  410. });
  411. return _facet;
  412. }
  413. self.getHistogramFacet = function () { // Should do multi histogram
  414. return self.getFacetByType('histogram-widget');
  415. }
  416. self.template.fields = ko.computed(function () {
  417. var _fields = [];
  418. $.each(self.template.fieldsAttributes(), function (index, field) {
  419. var position = self.template.fieldsSelected.indexOf(field.name());
  420. if (position != -1) {
  421. _fields[position] = field;
  422. }
  423. });
  424. return _fields;
  425. });
  426. self.getTemplateField = function (name) {
  427. var _field = null;
  428. $.each(self.template.fields(), function (index, field) {
  429. if (field.name() == name) {
  430. _field = field;
  431. return false;
  432. }
  433. });
  434. return _field;
  435. };
  436. self.template.fieldsModalFilter = ko.observable(""); // For UI
  437. self.template.fieldsModalType = ko.observable(""); // For UI
  438. self.template.fieldsAttributesFilter = ko.observable(""); // For UI
  439. self.template.filteredModalFields = ko.observableArray();
  440. self.template.filteredAttributeFields = ko.computed(function() {
  441. var _fields = [];
  442. $.each(self.template.fieldsAttributes(), function (index, field) {
  443. if (self.template.fieldsAttributesFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsAttributesFilter().toLowerCase()) > -1){
  444. _fields.push(field);
  445. }
  446. });
  447. return _fields;
  448. });
  449. self.template.availableWidgetFields = ko.computed(function() {
  450. if (self.template.fieldsModalType() == 'histogram-widget') {
  451. return vm.availableDateFields();
  452. }
  453. else if (self.template.fieldsModalType() == 'line-widget') {
  454. return vm.availableNumberFields();
  455. }
  456. else {
  457. return self.availableFacetFields();
  458. }
  459. });
  460. self.template.availableWidgetFieldsNames = ko.computed(function() {
  461. return $.map(self.template.availableWidgetFields(), function(field){
  462. return field.name();
  463. });
  464. });
  465. self.template.fieldsModalFilter.subscribe(function(value) {
  466. var _fields = [];
  467. var _availableFields = self.template.availableWidgetFields();
  468. $.each(_availableFields, function (index, field) {
  469. if (self.template.fieldsModalFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  470. _fields.push(field);
  471. }
  472. });
  473. self.template.filteredModalFields(_fields);
  474. });
  475. self.switchCollection = function() { // Long term would be to reload the page
  476. $.post("/search/get_collection", {
  477. name: self.name()
  478. }, function (data) {
  479. if (data.status == 0) {
  480. self.idField(data.collection.collection.idField);
  481. self.template.template(data.collection.collection.template.template);
  482. self.template.fieldsAttributes.removeAll();
  483. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  484. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  485. });
  486. self.fields.removeAll();
  487. $.each(data.collection.collection.fields, function(index, field) {
  488. self.fields.push(ko.mapping.fromJS(field));
  489. });
  490. }
  491. }).fail(function (xhr, textStatus, errorThrown) {});
  492. };
  493. function diff(A, B) {
  494. return A.filter(function (a) {
  495. return B.indexOf(a) == -1;
  496. });
  497. }
  498. function syncArray(currentObservable, newJson, isDynamic) {
  499. // Get names of fields
  500. var _currentFieldsNames = $.map(
  501. $.grep(currentObservable(), function(field) {
  502. return field.isDynamic() == isDynamic;
  503. }), function(field) {
  504. return field.name();
  505. });
  506. var _newFieldsNames = $.map(
  507. $.grep(newJson, function(field) {
  508. return field.isDynamic == isDynamic;
  509. }), function(field) {
  510. return field.name;
  511. });
  512. var _toDelete = diff(_currentFieldsNames, _newFieldsNames);
  513. var _toAdd = diff(_newFieldsNames, _currentFieldsNames);
  514. // Deleted fields
  515. $.each(currentObservable(), function(index, field) {
  516. if (_toDelete.indexOf(field.name()) != -1) {
  517. currentObservable.remove(field);
  518. }
  519. });
  520. // New fields
  521. $.each(newJson, function(index, field) {
  522. if (_toAdd.indexOf(field.name) != -1) {
  523. currentObservable.push(ko.mapping.fromJS(field));
  524. }
  525. });
  526. }
  527. self.syncFields = function() {
  528. $.post("/search/get_collection", {
  529. name: self.name()
  530. }, function (data) {
  531. if (data.status == 0) {
  532. self.idField(data.collection.collection.idField);
  533. syncArray(self.template.fieldsAttributes, data.collection.collection.template.fieldsAttributes, false);
  534. syncArray(self.fields, data.collection.collection.fields, false);
  535. }
  536. // After sync the dynamic fields
  537. self.syncDynamicFields()
  538. }).fail(function (xhr, textStatus, errorThrown) {});
  539. };
  540. self.syncDynamicFields = function () {
  541. $.post("/search/index/fields/dynamic", {
  542. name: self.name()
  543. }, function (data) {
  544. if (data.status == 0) {
  545. syncArray(self.template.fieldsAttributes, data.gridlayout_header_fields, true);
  546. syncArray(self.fields, data.fields, true);
  547. }
  548. }).fail(function (xhr, textStatus, errorThrown) {});
  549. };
  550. self.toggleSortColumnGridLayout = function (template_field) {
  551. if (! template_field.sort.direction()) {
  552. template_field.sort.direction('desc');
  553. } else if (template_field.sort.direction() == 'desc') {
  554. template_field.sort.direction('asc');
  555. } else {
  556. template_field.sort.direction(null);
  557. }
  558. $(document).trigger("setResultsHeight");
  559. vm.search();
  560. };
  561. self.toggleSortFacet = function (facet_field, event) {
  562. if (facet_field.properties.sort() == 'desc') {
  563. facet_field.properties.sort('asc');
  564. } else {
  565. facet_field.properties.sort('desc');
  566. }
  567. $(event.target).button('loading');
  568. vm.search();
  569. };
  570. self.toggleRangeFacet = function (facet_field, event) {
  571. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  572. if (facet_field.type() == 'field') {
  573. facet_field.type('range');
  574. } else if (facet_field.type() == 'range') {
  575. facet_field.type('field')
  576. }
  577. $(event.target).button('loading');
  578. vm.search();
  579. };
  580. self.selectTimelineFacet = function (data) { // alert(ko.mapping.toJSON(data));
  581. var facet = self.getFacetById(data.widget_id);
  582. facet.properties.start(data.from);
  583. facet.properties.end(data.to);
  584. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  585. $.ajax({
  586. type: "POST",
  587. url: "/search/get_range_facet",
  588. data: {
  589. collection: ko.mapping.toJSON(self),
  590. facet: ko.mapping.toJSON(facet),
  591. action: 'select'
  592. },
  593. success: function (data) {
  594. if (data.status == 0) {
  595. facet.properties.gap(data.properties.gap);
  596. }
  597. },
  598. async: false
  599. });
  600. vm.search();
  601. }
  602. self.timeLineZoom = function (facet_json) {
  603. var facet = self.getFacetById(facet_json.id);
  604. facet.properties.start(facet.from);
  605. facet.properties.end(facet.to);
  606. $.ajax({
  607. type: "POST",
  608. url: "/search/get_range_facet",
  609. data: {
  610. collection: ko.mapping.toJSON(self),
  611. facet: ko.mapping.toJSON(facet),
  612. action: "zoom_out"
  613. },
  614. success: function (data) {
  615. if (data.status == 0) {
  616. facet.properties.start(data.properties.start);
  617. facet.properties.end(data.properties.end);
  618. facet.properties.gap(data.properties.gap);
  619. }
  620. },
  621. async: false
  622. });
  623. vm.search();
  624. }
  625. self.translateSelectedField = function (index, direction) {
  626. var array = self.template.fieldsSelected();
  627. if (direction == 'left') {
  628. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  629. } else {
  630. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  631. }
  632. vm.search();
  633. };
  634. self.upDownFacetLimit = function (facet_id, direction) {
  635. var facet = self.getFacetById(facet_id);
  636. if (facet.properties.prevLimit == undefined) {
  637. facet.properties.prevLimit = facet.properties.limit();
  638. }
  639. if (direction == 'up') {
  640. facet.properties.limit(facet.properties.limit() + 10);
  641. } else {
  642. facet.properties.limit(facet.properties.limit() - 10);
  643. }
  644. vm.search();
  645. };
  646. };
  647. var NewTemplate = function (vm, initial) {
  648. var self = this;
  649. self.collections = ko.mapping.fromJS(initial.collections);
  650. self.layout = initial.layout;
  651. self.inited = ko.observable(self.collections().length > 0); // No collection if not a new dashboard
  652. self.init = function() {
  653. if (self.inited()) {
  654. // If new dashboard
  655. vm.collection.name.subscribe(function(newValue) {
  656. vm.collection.label(newValue);
  657. vm.collection.switchCollection();
  658. vm.search();
  659. });
  660. } else {
  661. self.syncCollections();
  662. }
  663. if (initial.autoLoad) {
  664. magicLayout(vm);
  665. }
  666. };
  667. self.syncCollections = function () {
  668. $.post("/search/get_collections", {
  669. },function (data) {
  670. if (data.status == 0) {
  671. // Sync new and old names
  672. $.each(data.collection, function(index, name) {
  673. if (self.collections.indexOf(name) == -1) {
  674. self.collections.push(name);
  675. }
  676. });
  677. $.each(self.collections(), function(index, collection) {
  678. if (data.collection.indexOf(collection) == -1) {
  679. self.collections.remove(collection);
  680. }
  681. });
  682. }
  683. else {
  684. $(document).trigger("error", data.message);
  685. }
  686. }).fail(function (xhr, textStatus, errorThrown) {
  687. $(document).trigger("error", xhr.responseText);
  688. }).done(function() {
  689. self.inited(true);
  690. });
  691. };
  692. };
  693. var DATE_TYPES = ['date', 'tdate'];
  694. var NUMBER_TYPES = ['int', 'tint', 'long', 'tlong', 'float', 'tfloat'];
  695. var RANGE_SELECTABLE_WIDGETS = ['histogram-widget', 'bar-widget', 'line-widget'];
  696. var SearchViewModel = function (collection_json, query_json, initial_json) {
  697. var self = this;
  698. // Models
  699. self.collection = new Collection(self, collection_json.collection);
  700. self.query = new Query(self, query_json);
  701. self.initial = new NewTemplate(self, initial_json);
  702. // UI
  703. self.response = ko.observable({});
  704. self.results = ko.observableArray([]);
  705. self.norm_facets = ko.computed(function () {
  706. return self.response().normalized_facets;
  707. });
  708. self.getFacetFromQuery = function (facet_id) {
  709. var _facet = null;
  710. if (self.norm_facets() !== undefined) {
  711. $.each(self.norm_facets(), function (index, norm_facet) {
  712. if (norm_facet.id == facet_id) {
  713. _facet = norm_facet;
  714. }
  715. });
  716. }
  717. return _facet;
  718. };
  719. self.toggledGridlayoutResultChevron = ko.observable(false);
  720. self.enableGridlayoutResultChevron = function() {
  721. self.toggledGridlayoutResultChevron(true);
  722. };
  723. self.disableGridlayoutResultChevron = function() {
  724. self.toggledGridlayoutResultChevron(false);
  725. };
  726. self.previewColumns = ko.observable("");
  727. self.columns = ko.observable([]);
  728. loadLayout(self, collection_json.layout);
  729. self.isEditing = ko.observable(false);
  730. self.toggleEditing = function () {
  731. self.isEditing(!self.isEditing());
  732. };
  733. self.isRetrievingResults = ko.observable(false);
  734. self.draggableHit = ko.observable(new Widget(12, UUID(), "Hit Count", "hit-widget"));
  735. self.draggableFacet = ko.observable(new Widget(12, UUID(), "Facet", "facet-widget"));
  736. self.draggableResultset = ko.observable(new Widget(12, UUID(), "Grid Results", "resultset-widget"));
  737. self.draggableHtmlResultset = ko.observable(new Widget(12, UUID(), "HTML Results", "html-resultset-widget"));
  738. self.draggableHistogram = ko.observable(new Widget(12, UUID(), "Histogram", "histogram-widget"));
  739. self.draggableBar = ko.observable(new Widget(12, UUID(), "Bar Chart", "bar-widget"));
  740. self.draggableMap = ko.observable(new Widget(12, UUID(), "Map", "map-widget"));
  741. self.draggableLine = ko.observable(new Widget(12, UUID(), "Line Chart", "line-widget"));
  742. self.draggablePie = ko.observable(new Widget(12, UUID(), "Pie Chart", "pie-widget"));
  743. self.draggableFilter = ko.observable(new Widget(12, UUID(), "Filter Bar", "filter-widget"));
  744. self.availableDateFields = ko.computed(function() {
  745. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPES.indexOf(field.type()) != -1; });
  746. });
  747. self.availableNumberFields = ko.computed(function() {
  748. return $.grep(self.collection.availableFacetFields(), function(field) { return NUMBER_TYPES.indexOf(field.type()) != -1; });
  749. });
  750. function getWidgets(equalsTo) {
  751. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  752. };
  753. self.availableDraggableResultset = ko.computed(function() {
  754. return getWidgets(function(widget){ return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  755. });
  756. self.availableDraggableFilter = ko.computed(function() {
  757. return getWidgets(function(widget){ return widget.widgetType() == 'filter-widget'; }).length == 0;
  758. });
  759. self.availableDraggableHistogram = ko.computed(function() {
  760. return getWidgets(function(widget){ return widget.widgetType() == 'histogram-widget'; }).length == 0 &&
  761. self.availableDateFields().length > 0;
  762. });
  763. self.availableDraggableNumbers = ko.computed(function() {
  764. return getWidgets(function(widget){ return widget.widgetType() == 'line-widget'; }).length == 0 &&
  765. self.availableNumberFields().length > 0;
  766. });
  767. self.availableDraggableChart = ko.computed(function() {
  768. return self.collection.availableFacetFields().length > 0;
  769. });
  770. self.init = function (callback) {
  771. self.initial.init();
  772. self.collection.syncFields();
  773. self.search(callback);
  774. }
  775. self.searchBtn = function () {
  776. self.query.start(0);
  777. self.search();
  778. };
  779. self.search = function (callback) {
  780. self.isRetrievingResults(true);
  781. $(".jHueNotify").hide();
  782. // Multi queries
  783. var multiQs = [];
  784. var multiQ = self.query.getMultiq();
  785. if (multiQ != null) {
  786. var facet = {};
  787. var queries = [];
  788. if (multiQ == 'query') {
  789. queries = self.query.qs();
  790. } else {
  791. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  792. queries = facet.filter();
  793. }
  794. multiQs = $.map(queries, function(qdata) {
  795. return $.post("/search/get_timeline", {
  796. collection: ko.mapping.toJSON(self.collection),
  797. query: ko.mapping.toJSON(self.query),
  798. facet: ko.mapping.toJSON(facet),
  799. qdata: ko.mapping.toJSON(qdata),
  800. multiQ: multiQ
  801. }, function (data) {return data});
  802. });
  803. }
  804. $.when.apply($, [
  805. $.post("/search/search", {
  806. collection: ko.mapping.toJSON(self.collection),
  807. query: ko.mapping.toJSON(self.query),
  808. layout: ko.mapping.toJSON(self.columns)
  809. }, function (data) {
  810. if (typeof callback != undefined && callback != null){
  811. callback(data);
  812. }
  813. self.response(data);
  814. self.results.removeAll();
  815. if (data.error) {
  816. $(document).trigger("error", data.error);
  817. }
  818. else {
  819. if (self.collection.template.isGridLayout()) {
  820. // Table view
  821. $.each(data.response.docs, function (index, item) {
  822. var row = [];
  823. var fields = self.collection.template.fieldsSelected();
  824. // Display selected fields or whole json document
  825. if (fields.length != 0) {
  826. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  827. row.push(item[field]);
  828. });
  829. } else {
  830. row.push(ko.mapping.toJSON(item));
  831. }
  832. var doc = {'id': item[self.collection.idField()], 'row': row};
  833. self.results.push(doc);
  834. });
  835. }
  836. else {
  837. // Template view
  838. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  839. $.each(data.response.docs, function (index, item) {
  840. // fix the fields that contain dots in the name
  841. addTemplateFunctions(item);
  842. self.results.push(Mustache.render(_mustacheTmpl, item));
  843. });
  844. }
  845. self.isRetrievingResults(false);
  846. }
  847. })
  848. ].concat(multiQs)
  849. )
  850. .done(function() {
  851. if (arguments[0] instanceof Array) { // If multi queries
  852. var histoFacetId = self.collection.getHistogramFacet().id();
  853. var histoFacet = self.getFacetFromQuery(histoFacetId);
  854. for (var i = 1; i < arguments.length; i++) {
  855. histoFacet.extraSeries.push(arguments[i][0]['series']);
  856. }
  857. self.response.valueHasMutated();
  858. }
  859. })
  860. .fail(function (xhr, textStatus, errorThrown) {
  861. $(document).trigger("error", xhr.responseText);
  862. })
  863. .always(function () {
  864. $('.btn-loading').button('reset');
  865. });
  866. };
  867. self.removeWidget = function (widget_json) {
  868. self.collection.removeFacet(widget_json.id);
  869. self.query.removeFilter(widget_json);
  870. self.removeWidgetById(widget_json.id());
  871. self.search();
  872. }
  873. self.getWidgetById = function (widget_id) {
  874. var _widget = null;
  875. $.each(self.columns(), function (i, col) {
  876. $.each(col.rows(), function (j, row) {
  877. $.each(row.widgets(), function (z, widget) {
  878. if (widget.id() == widget_id){
  879. _widget = widget;
  880. }
  881. });
  882. });
  883. });
  884. return _widget;
  885. }
  886. self.removeWidgetById = function (widget_id) {
  887. $.each(self.columns(), function (i, col) {
  888. $.each(col.rows(), function (j, row) {
  889. $.each(row.widgets(), function (z, widget) {
  890. if (widget.id() == widget_id){
  891. row.widgets.remove(widget);
  892. }
  893. });
  894. });
  895. });
  896. }
  897. self.getDocument = function (doc) {
  898. $.post("/search/get_document", {
  899. collection: ko.mapping.toJSON(self.collection),
  900. id: doc.id
  901. },function (data) {
  902. if (data.status == 0) {
  903. $(document).trigger("showDoc", data.doc.doc);
  904. }
  905. else if (data.status == 1) {
  906. $(document).trigger("info", data.message);
  907. }
  908. else {
  909. $(document).trigger("error", data.message);
  910. }
  911. }).fail(function (xhr, textStatus, errorThrown) {
  912. $(document).trigger("error", xhr.responseText);
  913. });
  914. };
  915. self.save = function () {
  916. $.post("/search/save", {
  917. collection: ko.mapping.toJSON(self.collection),
  918. layout: ko.mapping.toJSON(self.columns)
  919. },function (data) {
  920. if (data.status == 0) {
  921. self.collection.id = data.id;
  922. $(document).trigger("info", data.message);
  923. if (window.location.search.indexOf("collection") == -1){
  924. window.location.hash = '#collection=' + data.id;
  925. }
  926. }
  927. else {
  928. $(document).trigger("error", data.message);
  929. }
  930. }).fail(function (xhr, textStatus, errorThrown) {
  931. $(document).trigger("error", xhr.responseText);
  932. });
  933. };
  934. };