search.ko.js 33 KB

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