search.ko.js 34 KB

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