search.ko.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. return false;
  283. }
  284. });
  285. };
  286. self.paginate = function (direction) {
  287. if (direction == 'next') {
  288. self.start(self.start() + vm.collection.template.rows() * 1.0);
  289. } else {
  290. self.start(self.start() - vm.collection.template.rows() * 1.0);
  291. }
  292. vm.search();
  293. };
  294. };
  295. var Collection = function (vm, collection) {
  296. var self = this;
  297. self.id = collection.id;
  298. self.name = ko.mapping.fromJS(collection.name);
  299. self.label = ko.mapping.fromJS(collection.label);
  300. self.enabled = ko.mapping.fromJS(collection.enabled);
  301. self.idField = ko.observable(collection.idField);
  302. self.template = ko.mapping.fromJS(collection.template);
  303. self.template.fieldsSelected.subscribe(function () {
  304. vm.search();
  305. });
  306. self.template.template.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  307. self.template.template.subscribe(function () {
  308. vm.search();
  309. });
  310. self.template.isGridLayout.subscribe(function () {
  311. vm.search();
  312. });
  313. self.template.selectedVisualField = ko.observable();
  314. self.template.selectedVisualFunction = ko.observable();
  315. self.template.selectedVisualFunction.subscribe(function (newValue) {
  316. var _vf = $("#visualFunctions");
  317. _vf.siblings(".muted").text(_vf.find(":selected").attr("title"));
  318. });
  319. self.template.selectedSourceField = ko.observable();
  320. self.template.selectedSourceFunction = ko.observable();
  321. self.template.selectedSourceFunction.subscribe(function (newValue) {
  322. var _sf = $("#sourceFunctions");
  323. _sf.siblings(".muted").text(_sf.find(":selected").attr("title"));
  324. });
  325. self.template.addFieldToVisual = function () {
  326. $(document).trigger("addFieldToVisual", self.template.selectedVisualField());
  327. };
  328. self.template.addFunctionToVisual = function () {
  329. $(document).trigger("addFunctionToVisual", self.template.selectedVisualFunction());
  330. };
  331. self.template.addFieldToSource = function () {
  332. $(document).trigger("addFieldToSource", self.template.selectedSourceField());
  333. };
  334. self.template.addFunctionToSource = function () {
  335. $(document).trigger("addFunctionToSource", self.template.selectedSourceFunction());
  336. };
  337. self.facets = ko.mapping.fromJS(collection.facets);
  338. $.each(self.facets(), function (index, facet) {
  339. facet.field.subscribe(function () {
  340. vm.search();
  341. });
  342. });
  343. self.template.rows.subscribe(function(){
  344. vm.search();
  345. });
  346. self.template.rows.extend({rateLimit: {timeout: 1500, method: "notifyWhenChangesStop"}});
  347. self.fields = ko.mapping.fromJS(collection.fields);
  348. self.availableFacetFields = ko.computed(function() {
  349. var facetFieldNames = $.map(self.facets(), function(facet) {
  350. return facet.field(); //filter out text_general
  351. });
  352. return $.grep(self.fields(), function(field) {
  353. return facetFieldNames.indexOf(field.name()) == -1;
  354. });
  355. });
  356. self.selectedDocument = ko.observable({});
  357. self.addFacet = function (facet_json) {
  358. self.removeFacet(function(){return facet_json.widget_id});
  359. $.post("/search/template/new_facet", {
  360. "collection": ko.mapping.toJSON(self),
  361. "id": facet_json.widget_id,
  362. "label": facet_json.name,
  363. "field": facet_json.name,
  364. "widget_type": facet_json.widgetType
  365. }, function (data) {
  366. if (data.status == 0) {
  367. var facet = ko.mapping.fromJS(data.facet);
  368. facet.field.subscribe(function () {
  369. vm.search();
  370. });
  371. self.facets.push(facet);
  372. vm.search();
  373. } else {
  374. $(document).trigger("error", data.message);
  375. }
  376. }).fail(function (xhr, textStatus, errorThrown) {});
  377. };
  378. self.removeFacet = function (widget_id) {
  379. $.each(self.facets(), function (index, facet) {
  380. if (facet.id() == widget_id()) {
  381. self.facets.remove(facet);
  382. return false;
  383. }
  384. });
  385. }
  386. self.getFacetById = function (facet_id) {
  387. var _facet = null;
  388. $.each(self.facets(), function (index, facet) {
  389. if (facet.id() == facet_id) {
  390. _facet = facet;
  391. return false;
  392. }
  393. });
  394. return _facet;
  395. }
  396. self.getFacetByType = function (facetType) {
  397. var _facet = null;
  398. $.each(self.facets(), function (index, facet) {
  399. if (facet.widgetType() == facetType) {
  400. _facet = facet;
  401. return false;
  402. }
  403. });
  404. return _facet;
  405. }
  406. self.getHistogramFacet = function () { // might remove when list of available widgets
  407. return self.getFacetByType('histogram-widget');
  408. }
  409. self.template.fields = ko.computed(function () {
  410. var _fields = [];
  411. $.each(self.template.fieldsAttributes(), function (index, field) {
  412. var position = self.template.fieldsSelected.indexOf(field.name());
  413. if (position != -1) {
  414. _fields[position] = field;
  415. }
  416. });
  417. return _fields;
  418. });
  419. self.getTemplateField = function (name) {
  420. var _field = null;
  421. $.each(self.template.fields(), function (index, field) {
  422. if (field.name() == name) {
  423. _field = field;
  424. return false;
  425. }
  426. });
  427. return _field;
  428. };
  429. self.template.fieldsModalFilter = ko.observable(""); // For UI
  430. self.template.fieldsModalType = ko.observable(""); // For UI
  431. self.template.fieldsAttributesFilter = ko.observable(""); // For UI
  432. self.template.filteredModalFields = ko.observableArray();
  433. self.template.filteredAttributeFields = ko.computed(function() {
  434. var _fields = [];
  435. $.each(self.template.fieldsAttributes(), function (index, field) {
  436. if (self.template.fieldsAttributesFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsAttributesFilter().toLowerCase()) > -1){
  437. _fields.push(field);
  438. }
  439. });
  440. return _fields;
  441. });
  442. self.template.availableWidgetFields = ko.computed(function() {
  443. return self.template.fieldsModalType() == 'histogram-widget'? vm.availableDateFields() : self.availableFacetFields();
  444. });
  445. self.template.availableWidgetFieldsNames = ko.computed(function() {
  446. return $.map(self.template.availableWidgetFields(), function(field){
  447. return field.name();
  448. });
  449. });
  450. self.template.fieldsModalFilter.subscribe(function(value) {
  451. var _fields = [];
  452. var _availableFields = self.template.availableWidgetFields();
  453. $.each(_availableFields, function (index, field) {
  454. if (self.template.fieldsModalFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  455. _fields.push(field);
  456. }
  457. });
  458. self.template.filteredModalFields(_fields);
  459. });
  460. self.switchCollection = function() {
  461. $.post("/search/get_collection/", {
  462. name: self.name()
  463. }, function (data) {
  464. if (data.status == 0) {
  465. self.idField(data.collection.collection.idField);
  466. self.template.template(data.collection.collection.template.template);
  467. self.template.fieldsAttributes.removeAll();
  468. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  469. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  470. });
  471. self.fields.removeAll();
  472. $.each(data.collection.collection.fields, function(index, field) {
  473. self.fields.push(ko.mapping.fromJS(field));
  474. });
  475. }
  476. }).fail(function (xhr, textStatus, errorThrown) {});
  477. };
  478. function diff(A, B) {
  479. return A.filter(function (a) {
  480. return B.indexOf(a) == -1;
  481. });
  482. }
  483. function syncArray(currentObservable, newJson, isDynamic) {
  484. // Get names of fields
  485. var _currentFieldsNames = $.map(
  486. $.grep(currentObservable(), function(field) {
  487. return field.isDynamic() == isDynamic;
  488. }), function(field) {
  489. return field.name();
  490. });
  491. var _newFieldsNames = $.map(
  492. $.grep(newJson, function(field) {
  493. return field.isDynamic == isDynamic;
  494. }), function(field) {
  495. return field.name;
  496. });
  497. var _toDelete = diff(_currentFieldsNames, _newFieldsNames);
  498. var _toAdd = diff(_newFieldsNames, _currentFieldsNames);
  499. // Deleted fields
  500. $.each(currentObservable(), function(index, field) {
  501. if (_toDelete.indexOf(field.name()) != -1) {
  502. currentObservable.remove(field);
  503. }
  504. });
  505. // New fields
  506. $.each(newJson, function(index, field) {
  507. if (_toAdd.indexOf(field.name) != -1) {
  508. currentObservable.push(ko.mapping.fromJS(field));
  509. }
  510. });
  511. }
  512. self.syncFields = function() {
  513. $.post("/search/get_collection/", {
  514. name: self.name()
  515. }, function (data) {
  516. if (data.status == 0) {
  517. self.idField(data.collection.collection.idField);
  518. syncArray(self.template.fieldsAttributes, data.collection.collection.template.fieldsAttributes, false);
  519. syncArray(self.fields, data.collection.collection.fields, false);
  520. }
  521. // After sync the dynamic fields
  522. self.syncDynamicFields()
  523. }).fail(function (xhr, textStatus, errorThrown) {});
  524. };
  525. self.syncDynamicFields = function () {
  526. $.post("/search/index/fields/dynamic", {
  527. name: self.name()
  528. }, function (data) {
  529. if (data.status == 0) {
  530. syncArray(self.template.fieldsAttributes, data.gridlayout_header_fields, true);
  531. syncArray(self.fields, data.fields, true);
  532. }
  533. }).fail(function (xhr, textStatus, errorThrown) {});
  534. };
  535. self.toggleSortColumnGridLayout = function (template_field) {
  536. if (! template_field.sort.direction()) {
  537. template_field.sort.direction('desc');
  538. } else if (template_field.sort.direction() == 'desc') {
  539. template_field.sort.direction('asc');
  540. } else {
  541. template_field.sort.direction(null);
  542. }
  543. vm.search();
  544. };
  545. self.toggleSortFacet = function (facet_field, event) {
  546. if (facet_field.properties.sort() == 'desc') {
  547. facet_field.properties.sort('asc');
  548. } else {
  549. facet_field.properties.sort('desc');
  550. }
  551. $(event.target).button('loading');
  552. vm.search();
  553. };
  554. self.toggleRangeFacet = function (facet_field, event) {
  555. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  556. if (facet_field.type() == 'field') {
  557. facet_field.type('range');
  558. } else if (facet_field.type() == 'range') {
  559. facet_field.type('field')
  560. }
  561. $(event.target).button('loading');
  562. vm.search();
  563. };
  564. self.selectTimelineFacet = function (data) { // alert(ko.mapping.toJSON(facet));
  565. var facet = self.getFacetById(data.widget_id);
  566. facet.properties.start(data.from);
  567. facet.properties.end(data.to);
  568. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  569. $.ajax({
  570. type: "POST",
  571. url: "/search/get_range_facet",
  572. data: {
  573. collection: ko.mapping.toJSON(self),
  574. facet: ko.mapping.toJSON(facet),
  575. action: 'select'
  576. },
  577. success: function (data) {
  578. if (data.status == 0) {
  579. facet.properties.gap(data.properties.gap);
  580. }
  581. },
  582. async: false
  583. });
  584. vm.search();
  585. }
  586. self.timeLineZoom = function (facet_json) {
  587. var facet = self.getFacetById(facet_json.id);
  588. facet.properties.start(facet.from);
  589. facet.properties.end(facet.to);
  590. $.ajax({
  591. type: "POST",
  592. url: "/search/get_range_facet",
  593. data: {
  594. collection: ko.mapping.toJSON(self),
  595. facet: ko.mapping.toJSON(facet),
  596. action: "zoom_out"
  597. },
  598. success: function (data) {
  599. if (data.status == 0) {
  600. facet.properties.start(data.properties.start);
  601. facet.properties.end(data.properties.end);
  602. facet.properties.gap(data.properties.gap);
  603. }
  604. },
  605. async: false
  606. });
  607. vm.search();
  608. }
  609. self.translateSelectedField = function (index, direction) {
  610. var array = self.template.fieldsSelected();
  611. if (direction == 'left') {
  612. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  613. } else {
  614. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  615. }
  616. vm.search();
  617. };
  618. self.upDownFacetLimit = function (facet_id, direction) {
  619. var facet = self.getFacetById(facet_id);
  620. if (facet.properties.prevLimit == undefined) {
  621. facet.properties.prevLimit = facet.properties.limit();
  622. }
  623. if (direction == 'up') {
  624. facet.properties.limit(facet.properties.limit() + 10);
  625. } else {
  626. facet.properties.limit(facet.properties.limit() - 10);
  627. }
  628. vm.search();
  629. };
  630. };
  631. var NewTemplate = function (vm, initial) {
  632. var self = this;
  633. self.collections = ko.mapping.fromJS(initial.collections);
  634. self.layout = initial.layout;
  635. if (self.collections) {
  636. vm.collection.name.subscribe(function (newValue) {
  637. vm.collection.label(newValue);
  638. vm.collection.switchCollection();
  639. vm.changeCollection(false);
  640. vm.search();
  641. });
  642. }
  643. self.init = function() {
  644. if (initial.autoLoad) {
  645. magicLayout(vm);
  646. }
  647. };
  648. };
  649. var DATE_TYPE = ['date', 'tdate'];
  650. var SearchViewModel = function (collection_json, query_json, initial_json) {
  651. var self = this;
  652. // Models
  653. self.collection = new Collection(self, collection_json.collection);
  654. self.query = new Query(self, query_json);
  655. self.initial = new NewTemplate(self, initial_json);
  656. // UI
  657. self.response = ko.observable({});
  658. self.results = ko.observableArray([]);
  659. self.norm_facets = ko.computed(function () {
  660. return self.response().normalized_facets;
  661. });
  662. self.getFacetFromQuery = function (facet_id) {
  663. var _facet = null;
  664. if (self.norm_facets() !== undefined) {
  665. $.each(self.norm_facets(), function (index, norm_facet) {
  666. if (norm_facet.id == facet_id) {
  667. _facet = norm_facet;
  668. }
  669. });
  670. }
  671. return _facet;
  672. };
  673. self.changeCollection = ko.observable(false);
  674. self.toggledGridlayoutResultChevron = ko.observable(false);
  675. self.enableGridlayoutResultChevron = function() {
  676. self.toggledGridlayoutResultChevron(true);
  677. };
  678. self.disableGridlayoutResultChevron = function() {
  679. self.toggledGridlayoutResultChevron(false);
  680. };
  681. self.previewColumns = ko.observable("");
  682. self.columns = ko.observable([]);
  683. loadLayout(self, collection_json.layout);
  684. self.isEditing = ko.observable(false);
  685. self.toggleEditing = function () {
  686. self.isEditing(!self.isEditing());
  687. };
  688. self.isRetrievingResults = ko.observable(false);
  689. self.draggableHit = ko.observable(new Widget(12, UUID(), "Hit Count", "hit-widget"));
  690. self.draggableFacet = ko.observable(new Widget(12, UUID(), "Facet", "facet-widget"));
  691. self.draggableResultset = ko.observable(new Widget(12, UUID(), "Grid Results", "resultset-widget"));
  692. self.draggableHtmlResultset = ko.observable(new Widget(12, UUID(), "HTML Results", "html-resultset-widget"));
  693. self.draggableHistogram = ko.observable(new Widget(12, UUID(), "Histogram", "histogram-widget"));
  694. self.draggableBar = ko.observable(new Widget(12, UUID(), "Bar Chart", "bar-widget"));
  695. self.draggableMap = ko.observable(new Widget(12, UUID(), "Map", "map-widget"));
  696. self.draggableLine = ko.observable(new Widget(12, UUID(), "Line Chart", "line-widget"));
  697. self.draggablePie = ko.observable(new Widget(12, UUID(), "Pie Chart", "pie-widget"));
  698. self.draggableFilter = ko.observable(new Widget(12, UUID(), "Filter Bar", "filter-widget"));
  699. self.availableDateFields = ko.computed(function() {
  700. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPE.indexOf(field.type()) != -1; });
  701. });
  702. function getWidgets(equalsTo) {
  703. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  704. };
  705. self.availableDraggableResultset = ko.computed(function() {
  706. return getWidgets(function(widget){ return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  707. });
  708. self.availableDraggableFilter = ko.computed(function() {
  709. return getWidgets(function(widget){ return widget.widgetType() == 'filter-widget'; }).length == 0;
  710. });
  711. self.availableDraggableHistogram = ko.computed(function() {
  712. return getWidgets(function(widget){ return widget.widgetType() == 'histogram-widget'; }).length == 0 &&
  713. self.availableDateFields().length > 0;
  714. });
  715. self.availableDraggableChart = ko.computed(function() {
  716. return self.collection.availableFacetFields().length > 0;
  717. });
  718. self.init = function (callback) {
  719. self.initial.init();
  720. self.collection.syncFields();
  721. self.isEditing(true);
  722. self.search(callback);
  723. }
  724. self.searchBtn = function () {
  725. self.query.start(0);
  726. self.search();
  727. };
  728. self.search = function (callback) {
  729. self.isRetrievingResults(true);
  730. $(".jHueNotify").hide();
  731. // Multi queries
  732. var multiQs = [];
  733. var multiQ = self.query.getMultiq();
  734. if (multiQ != null) {
  735. var facet = {};
  736. var queries = [];
  737. if (multiQ == 'query') {
  738. queries = self.query.qs();
  739. } else {
  740. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  741. queries = facet.filter();
  742. }
  743. multiQs = $.map(queries, function(qdata) {
  744. return $.post("/search/get_timeline", {
  745. collection: ko.mapping.toJSON(self.collection),
  746. query: ko.mapping.toJSON(self.query),
  747. facet: ko.mapping.toJSON(facet),
  748. qdata: ko.mapping.toJSON(qdata),
  749. multiQ: multiQ
  750. }, function (data) {return data});
  751. });
  752. }
  753. $.when.apply($, [
  754. $.post("/search/search", {
  755. collection: ko.mapping.toJSON(self.collection),
  756. query: ko.mapping.toJSON(self.query),
  757. layout: ko.mapping.toJSON(self.columns)
  758. }, function (data) {
  759. if (typeof callback != undefined && callback != null){
  760. callback(data);
  761. }
  762. self.response(data);
  763. self.results.removeAll();
  764. if (data.error) {
  765. $(document).trigger("error", data.error);
  766. }
  767. else {
  768. if (self.collection.template.isGridLayout()) {
  769. // Table view
  770. $.each(data.response.docs, function (index, item) {
  771. var row = [];
  772. var fields = self.collection.template.fieldsSelected();
  773. // Display selected fields or whole json document
  774. if (fields.length != 0) {
  775. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  776. row.push(item[field]);
  777. });
  778. } else {
  779. row.push(ko.mapping.toJSON(item));
  780. }
  781. var doc = {'id': item[self.collection.idField()], 'row': row};
  782. self.results.push(doc);
  783. });
  784. }
  785. else {
  786. // Template view
  787. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  788. $.each(data.response.docs, function (index, item) {
  789. // fix the fields that contain dots in the name
  790. addTemplateFunctions(item);
  791. self.results.push(Mustache.render(_mustacheTmpl, item));
  792. });
  793. }
  794. self.isRetrievingResults(false);
  795. }
  796. })
  797. ].concat(multiQs)
  798. )
  799. .done(function() {
  800. if (arguments[0] instanceof Array) { // If multi queries
  801. var histoFacetId = self.collection.getHistogramFacet().id();
  802. var histoFacet = self.getFacetFromQuery(histoFacetId);
  803. for (var i = 1; i < arguments.length; i++) {
  804. histoFacet.extraSeries.push(arguments[i][0]['series']);
  805. }
  806. self.response.valueHasMutated();
  807. }
  808. })
  809. .fail(function (xhr, textStatus, errorThrown) {
  810. $(document).trigger("error", xhr.responseText);
  811. })
  812. .always(function () {
  813. $('.btn-loading').button('reset');
  814. });
  815. };
  816. self.removeWidget = function (widget_json) {
  817. self.collection.removeFacet(widget_json.id);
  818. self.query.removeFilter(widget_json);
  819. self.removeWidgetById(widget_json.id());
  820. self.search();
  821. }
  822. self.getWidgetById = function (widget_id) {
  823. var _widget = null;
  824. $.each(self.columns(), function (i, col) {
  825. $.each(col.rows(), function (j, row) {
  826. $.each(row.widgets(), function (z, widget) {
  827. if (widget.id() == widget_id){
  828. _widget = widget;
  829. }
  830. });
  831. });
  832. });
  833. return _widget;
  834. }
  835. self.removeWidgetById = function (widget_id) {
  836. $.each(self.columns(), function (i, col) {
  837. $.each(col.rows(), function (j, row) {
  838. $.each(row.widgets(), function (z, widget) {
  839. if (widget.id() == widget_id){
  840. row.widgets.remove(widget);
  841. }
  842. });
  843. });
  844. });
  845. }
  846. self.getDocument = function (doc) {
  847. $.post("/search/get_document", {
  848. collection: ko.mapping.toJSON(self.collection),
  849. id: doc.id
  850. },function (data) {
  851. if (data.status == 0) {
  852. $(document).trigger("showDoc", data.doc.doc);
  853. }
  854. else if (data.status == 1) {
  855. $(document).trigger("info", data.message);
  856. }
  857. else {
  858. $(document).trigger("error", data.message);
  859. }
  860. }).fail(function (xhr, textStatus, errorThrown) {
  861. $(document).trigger("error", xhr.responseText);
  862. });
  863. };
  864. self.save = function () {
  865. $.post("/search/save", {
  866. collection: ko.mapping.toJSON(self.collection),
  867. layout: ko.mapping.toJSON(self.columns)
  868. },function (data) {
  869. if (data.status == 0) {
  870. self.collection.id = data.id;
  871. $(document).trigger("info", data.message);
  872. if (window.location.search.indexOf("collection") == -1){
  873. window.location.hash = '#collection=' + data.id;
  874. }
  875. }
  876. else {
  877. $(document).trigger("error", data.message);
  878. }
  879. }).fail(function (xhr, textStatus, errorThrown) {
  880. $(document).trigger("error", xhr.responseText);
  881. });
  882. };
  883. };