search.ko.js 33 KB

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