search.ko.js 33 KB

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