search.ko.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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.klass = ko.computed(function () {
  22. return "card card-home card-column span" + self.size();
  23. });
  24. self.addEmptyRow = function () {
  25. self.addRow();
  26. };
  27. self.addRow = function (row) {
  28. if (typeof row == "undefined" || row == null) {
  29. row = new Row([]);
  30. }
  31. self.rows.push(row);
  32. };
  33. }
  34. var Row = function (widgets) {
  35. var self = this;
  36. self.widgets = ko.observableArray(widgets);
  37. self.addWidget = function (widget) {
  38. self.widgets.push(widget);
  39. };
  40. self.move = function (from, to) {
  41. try {
  42. viewModel.columns()[to].addRow(self);
  43. viewModel.columns()[from].rows.remove(self);
  44. }
  45. catch (exception) {
  46. }
  47. }
  48. self.moveDown = function (col, row) {
  49. var _i = col.rows().indexOf(row);
  50. if (_i < col.rows().length - 1) {
  51. var _arr = col.rows();
  52. col.rows.splice(_i, 2, _arr[_i + 1], _arr[_i]);
  53. }
  54. }
  55. self.moveUp = function (col, row) {
  56. var _i = col.rows().indexOf(row);
  57. if (_i >= 1) {
  58. var _arr = col.rows();
  59. col.rows.splice(_i - 1, 2, _arr[_i], _arr[_i - 1]);
  60. }
  61. }
  62. self.remove = function (col, row) {
  63. $.each(self.widgets(), function(i, widget) {
  64. viewModel.removeWidget(widget);
  65. });
  66. col.rows.remove(row);
  67. }
  68. }
  69. // A widget is generic. It has an id that refer to another object (e.g. facet) with the same id.
  70. var Widget = function (size, id, name, widgetType, properties, offset, loading) {
  71. var self = this;
  72. self.size = ko.observable(size).extend({ numeric: 0 });
  73. self.name = ko.observable(name);
  74. self.id = ko.observable(id);
  75. self.widgetType = ko.observable(typeof widgetType != "undefined" && widgetType != null ? widgetType : "empty-widget");
  76. self.properties = ko.observable(typeof properties != "undefined" && properties != null ? properties : {});
  77. self.offset = ko.observable(typeof offset != "undefined" && offset != null ? offset : 0).extend({ numeric: 0 });
  78. self.isLoading = ko.observable(typeof loading != "undefined" && loading != null ? loading : false);
  79. self.klass = ko.computed(function () {
  80. return "card card-widget span" + self.size() + (self.offset() * 1 > 0 ? " offset" + self.offset() : "");
  81. });
  82. self.expand = function () {
  83. self.size(self.size() + 1);
  84. }
  85. self.compress = function () {
  86. self.size(self.size() - 1);
  87. }
  88. self.moveLeft = function () {
  89. self.offset(self.offset() - 1);
  90. }
  91. self.moveRight = function () {
  92. self.offset(self.offset() + 1);
  93. }
  94. self.remove = function (row, widget) {
  95. viewModel.removeWidget(widget);
  96. row.widgets.remove(widget);
  97. }
  98. };
  99. Widget.prototype.clone = function () {
  100. return new Widget(this.size(), UUID(), this.name(), this.widgetType());
  101. };
  102. function fullLayout() {
  103. setLayout([12]);
  104. }
  105. function oneThirdLeftLayout() {
  106. setLayout([2, 10]);
  107. }
  108. function oneThirdRightLayout() {
  109. setLayout([9, 3]);
  110. }
  111. function magicLayout(vm) {
  112. loadLayout(vm, vm.initial.layout);
  113. }
  114. function setLayout(colSizes) {
  115. // Save previous widgets
  116. var _allRows = [];
  117. $(viewModel.columns()).each(function (cnt, col) {
  118. var _tRows = [];
  119. $(col.rows()).each(function (icnt, row) {
  120. if (row.widgets().length > 0) {
  121. _tRows.push(row);
  122. }
  123. });
  124. _allRows = _allRows.concat(_tRows);
  125. });
  126. var _cols = [];
  127. var _highestCol = {
  128. idx: -1,
  129. size: -1
  130. };
  131. $(colSizes).each(function (cnt, size) {
  132. _cols.push(new Column(size, []));
  133. if (size > _highestCol.size) {
  134. _highestCol.idx = cnt;
  135. _highestCol.size = size;
  136. }
  137. });
  138. if (_allRows.length > 0 && _highestCol.idx > -1) {
  139. _cols[_highestCol.idx].rows(_allRows);
  140. }
  141. $(_cols).each(function (cnt, col) {
  142. if (col.rows().length == 0) {
  143. col.rows([new Row([])]);
  144. }
  145. });
  146. viewModel.columns(_cols);
  147. }
  148. function loadLayout(viewModel, json_layout) {
  149. var _columns = [];
  150. $(json_layout).each(function (cnt, json_col) {
  151. var _rows = [];
  152. $(json_col.rows).each(function (rcnt, json_row) {
  153. var row = new Row();
  154. $(json_row.widgets).each(function (wcnt, widget) {
  155. row.addWidget(new Widget(widget.size, widget.id, widget.name, widget.widgetType, widget.properties, widget.offset, true));
  156. });
  157. _rows.push(row);
  158. });
  159. var column = new Column(json_col.size, _rows);
  160. _columns = _columns.concat(column);
  161. });
  162. viewModel.columns(_columns);
  163. }
  164. // End dashboard lib
  165. var Query = function (vm, query) {
  166. var self = this;
  167. self.qs = ko.mapping.fromJS(query.qs);
  168. self.fqs = ko.mapping.fromJS(query.fqs);
  169. var defaultMultiqGroup = {'id': 'query', 'label': 'query'};
  170. self.multiqs = ko.computed(function () { // List of widgets supporting multiqs
  171. var histogram_id = vm.collection.getHistogramFacet();
  172. return [defaultMultiqGroup].concat(
  173. $.map($.grep(self.fqs(), function(fq, i) {
  174. return (fq.type() == 'field' || fq.type() == 'range') && (histogram_id == null || histogram_id.id() != fq.id());
  175. }), function(fq) { return {'id': fq.id(), 'label': fq.field()} })
  176. );
  177. });
  178. self.selectedMultiq = ko.observable(defaultMultiqGroup);
  179. self.getFacetFilter = function (widget_id) {
  180. var _fq = null;
  181. $.each(self.fqs(), function (index, fq) {
  182. if (fq.id() == widget_id) {
  183. _fq = fq;
  184. return false;
  185. }
  186. });
  187. return _fq;
  188. };
  189. self.getMultiq = ko.computed(function () {
  190. if (self.selectedMultiq()) {
  191. if (self.selectedMultiq() == 'query') {
  192. if (self.qs().length >= 2) {
  193. return 'query';
  194. }
  195. } else {
  196. var facet = self.getFacetFilter(self.selectedMultiq());
  197. if (facet && facet.filter().length > 0) { // todo + histogram there?
  198. return 'facet';
  199. }
  200. }
  201. }
  202. return null;
  203. });
  204. self.selectedMultiq.subscribe(function () { // To keep below the computed
  205. vm.search();
  206. });
  207. self.addQ = function (data) {
  208. self.qs.push(ko.mapping.fromJS({'q': ''}));
  209. };
  210. self.removeQ = function (query) {
  211. self.qs.remove(query);
  212. };
  213. self.toggleFacet = function (data) {
  214. var fq = self.getFacetFilter(data.widget_id);
  215. if (fq == null) {
  216. self.fqs.push(ko.mapping.fromJS({
  217. 'id': data.widget_id,
  218. 'field': data.facet.cat,
  219. 'filter': [data.facet.value],
  220. 'type': 'field'
  221. }));
  222. } else {
  223. $.each(self.fqs(), function (index, fq) {
  224. if (fq.id() == data.widget_id) {
  225. if (fq.filter.indexOf(data.facet.value) > -1) {
  226. fq.filter.remove(data.facet.value);
  227. if (fq.filter().length == 0) {
  228. self.fqs.remove(fq);
  229. }
  230. } else {
  231. fq.filter.push(data.facet.value);
  232. }
  233. }
  234. });
  235. }
  236. vm.search();
  237. }
  238. self.selectRangeFacet = function (data) {
  239. if (data.force != undefined) {
  240. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  241. }
  242. var fq = self.getFacetFilter(data.widget_id);
  243. if (fq == null) {
  244. self.fqs.push(ko.mapping.fromJS({
  245. 'id': data.widget_id,
  246. 'field': data.cat,
  247. 'filter': [data.from],
  248. 'properties': [{'from': data.from, 'to': data.to}],
  249. 'type': 'range'
  250. }));
  251. } else {
  252. if (fq.filter().indexOf(data.from) > -1) { // Unselect
  253. fq.filter.remove(data.from);
  254. $.each(fq.properties(), function (index, prop) {
  255. if (prop && prop.from() == data.from) {
  256. fq.properties.remove(prop);
  257. }
  258. });
  259. if (fq.filter().length == 0) {
  260. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  261. }
  262. } else {
  263. fq.filter.push(data.from);
  264. fq.properties.push(ko.mapping.fromJS({'from': data.from, 'to': data.to}));
  265. }
  266. }
  267. if (data.no_refresh == undefined) {
  268. vm.search();
  269. }
  270. };
  271. self.removeFilter = function (data) {
  272. $.each(self.fqs(), function (index, fq) {
  273. if (fq.id() == data.id()) {
  274. self.fqs.remove(fq);
  275. return false;
  276. }
  277. });
  278. };
  279. };
  280. var Collection = function (vm, collection) {
  281. var self = this;
  282. self.id = collection.id;
  283. self.name = ko.mapping.fromJS(collection.name);
  284. self.label = ko.mapping.fromJS(collection.label);
  285. self.idField = collection.idField;
  286. self.template = ko.mapping.fromJS(collection.template);
  287. self.template.fieldsSelected.subscribe(function () {
  288. vm.search();
  289. });
  290. self.template.template.extend({ rateLimit: { method: "notifyWhenChangesStop", timeout: 400 } }); // hum?
  291. self.template.template.subscribe(function () {
  292. vm.search();
  293. });
  294. self.template.isGridLayout.subscribe(function () {
  295. vm.search();
  296. });
  297. self.facets = ko.mapping.fromJS(collection.facets);
  298. $.each(self.facets(), function (index, facet) {
  299. facet.field.subscribe(function () {
  300. vm.search();
  301. });
  302. });
  303. self.fields = ko.mapping.fromJS(collection.fields);
  304. self.availableFacetFields = ko.computed(function() {
  305. var facetFieldNames = $.map(self.facets(), function(facet) {
  306. return facet.field();
  307. });
  308. return $.grep(self.fields(), function(field) {
  309. return facetFieldNames.indexOf(field.name()) == -1;
  310. });
  311. });
  312. self.addFacet = function (facet_json) {
  313. $.post("/search/template/new_facet", {
  314. "collection": ko.mapping.toJSON(self),
  315. "id": facet_json.widget_id,
  316. "label": facet_json.name,
  317. "field": facet_json.name,
  318. "widget_type": facet_json.widgetType
  319. }, function (data) {
  320. if (data.status == 0) {
  321. var facet = ko.mapping.fromJS(data.facet);
  322. facet.field.subscribe(function () {
  323. vm.search();
  324. });
  325. self.facets.push(facet);
  326. vm.search();
  327. } else {
  328. $(document).trigger("error", data.message);
  329. }
  330. }).fail(function (xhr, textStatus, errorThrown) {});
  331. };
  332. self.removeFacet = function (widget_id) {
  333. $.each(self.facets(), function (index, facet) {
  334. if (facet.id() == widget_id()) {
  335. self.facets.remove(facet);
  336. return false;
  337. }
  338. });
  339. }
  340. self.getFacetById = function (facet_id) {
  341. var _facet = null;
  342. $.each(self.facets(), function (index, facet) {
  343. if (facet.id() == facet_id) {
  344. _facet = facet;
  345. return false;
  346. }
  347. });
  348. return _facet;
  349. }
  350. self.getFacetByType = function (facetType) {
  351. var _facet = null;
  352. $.each(self.facets(), function (index, facet) {
  353. if (facet.widgetType() == facetType) {
  354. _facet = facet;
  355. return false;
  356. }
  357. });
  358. return _facet;
  359. }
  360. self.getHistogramFacet = function () { // might remove when list of available widgets
  361. return self.getFacetByType('histogram-widget');
  362. }
  363. self.template.fields = ko.computed(function () {
  364. var _fields = [];
  365. $.each(self.template.fieldsAttributes(), function (index, field) {
  366. var position = self.template.fieldsSelected.indexOf(field.name());
  367. if (position != -1) {
  368. _fields[position] = field;
  369. }
  370. });
  371. return _fields;
  372. });
  373. self.getTemplateField = function (name) {
  374. var _field = null;
  375. $.each(self.template.fields(), function (index, field) {
  376. if (field.name() == name) {
  377. _field = field;
  378. return false;
  379. }
  380. });
  381. return _field;
  382. };
  383. self.template.fieldsModalFilter = ko.observable("");
  384. self.template.filteredFieldsAttributes = ko.observableArray(self.template.fieldsAttributes());
  385. self.template.fieldsModalFilter.subscribe(function(value){
  386. var _fields = [];
  387. $.each(self.template.fieldsAttributes(), function (index, field) {
  388. if (field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  389. _fields.push(field);
  390. }
  391. });
  392. self.template.filteredFieldsAttributes(_fields);
  393. });
  394. self.addDynamicFields = function () { // + Adding merge smartly if schema updated
  395. $.post("/search/index/" + self.id + "/fields/dynamic", {
  396. }, function (data) {
  397. if (data.status == 0) {
  398. $.each(data.dynamic_fields, function (index, field) {
  399. if (self.fields.indexOf(field) == -1) {
  400. self.fields.push(field);
  401. }
  402. });
  403. }
  404. }).fail(function (xhr, textStatus, errorThrown) {});
  405. }
  406. self.toggleSortColumnGridLayout = function (template_field) {
  407. if (! template_field.sort.direction()) {
  408. template_field.sort.direction('desc');
  409. } else if (template_field.sort.direction() == 'desc') {
  410. template_field.sort.direction('asc');
  411. } else {
  412. template_field.sort.direction(null);
  413. }
  414. vm.search();
  415. };
  416. self.toggleSortFacet = function (facet_field, event) {
  417. if (facet_field.properties.sort() == 'desc') {
  418. facet_field.properties.sort('asc');
  419. } else {
  420. facet_field.properties.sort('desc');
  421. }
  422. $(event.target).button('loading');
  423. vm.search();
  424. };
  425. self.toggleRangeFacet = function (facet_field, event) {
  426. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  427. if (facet_field.type() == 'field') {
  428. facet_field.type('range');
  429. } else if (facet_field.type() == 'range') {
  430. facet_field.type('field')
  431. }
  432. $(event.target).button('loading');
  433. vm.search();
  434. };
  435. self.selectTimelineFacet = function (data) { // alert(ko.mapping.toJSON(facet));
  436. var facet = self.getFacetById(data.widget_id);
  437. facet.properties.start(data.from);
  438. facet.properties.end(data.to);
  439. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  440. $.ajax({
  441. type: "POST",
  442. url: "/search/get_range_facet",
  443. data: {
  444. collection: ko.mapping.toJSON(self),
  445. facet: ko.mapping.toJSON(facet),
  446. action: 'select'
  447. },
  448. success: function (data) {
  449. if (data.status == 0) {
  450. facet.properties.gap(data.properties.gap);
  451. }
  452. },
  453. async: false
  454. });
  455. vm.search();
  456. }
  457. self.timeLineZoom = function (facet_json) {
  458. var facet = self.getFacetById(facet_json.id);
  459. facet.properties.start(facet.from);
  460. facet.properties.end(facet.to);
  461. $.ajax({
  462. type: "POST",
  463. url: "/search/get_range_facet",
  464. data: {
  465. collection: ko.mapping.toJSON(self),
  466. facet: ko.mapping.toJSON(facet),
  467. action: "zoom_out"
  468. },
  469. success: function (data) {
  470. if (data.status == 0) {
  471. facet.properties.start(data.properties.start);
  472. facet.properties.end(data.properties.end);
  473. facet.properties.gap(data.properties.gap);
  474. }
  475. },
  476. async: false
  477. });
  478. vm.search();
  479. }
  480. self.translateSelectedField = function (index, direction) {
  481. var array = self.template.fieldsSelected();
  482. if (direction == 'left') {
  483. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  484. } else {
  485. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  486. }
  487. vm.search();
  488. };
  489. };
  490. var NewTemplate = function (vm, initial) {
  491. var self = this;
  492. self.collections = ko.mapping.fromJS(initial.collections);
  493. self.collections.subscribe(function (newValue) {
  494. vm.collection.name(newValue);
  495. });
  496. self.layout = initial.layout;
  497. };
  498. var SearchViewModel = function (collection_json, query_json, initial_json) {
  499. var self = this;
  500. // Models
  501. self.collection = new Collection(self, collection_json.collection);
  502. self.query = new Query(self, query_json);
  503. self.initial = new NewTemplate(self, initial_json);
  504. if (initial_json.collections) {
  505. self.collection.name.subscribe(function (newValue) {
  506. self.collection.label(newValue);
  507. });
  508. }
  509. // UI
  510. self.response = ko.observable({});
  511. self.results = ko.observableArray([]);
  512. self.norm_facets = ko.computed(function () {
  513. return self.response().normalized_facets;
  514. });
  515. self.getFacetFromQuery = function (facet_id) {
  516. var _facet = null;
  517. if (self.norm_facets() !== undefined) {
  518. $.each(self.norm_facets(), function (index, norm_facet) {
  519. if (norm_facet.id == facet_id) {
  520. _facet = norm_facet;
  521. }
  522. });
  523. }
  524. return _facet;
  525. };
  526. self.previewColumns = ko.observable("");
  527. self.columns = ko.observable([]);
  528. loadLayout(self, collection_json.layout);
  529. self.isEditing = ko.observable(false);
  530. self.toggleEditing = function () {
  531. self.isEditing(!self.isEditing());
  532. };
  533. self.isRetrievingResults = ko.observable(false);
  534. self.draggableHit = ko.observable(new Widget(12, UUID(), "Hit Count", "hit-widget"));
  535. self.draggableFacet = ko.observable(new Widget(12, UUID(), "Facet", "facet-widget"));
  536. self.draggableResultset = ko.observable(new Widget(12, UUID(), "Grid Results", "resultset-widget"));
  537. self.draggableHtmlResultset = ko.observable(new Widget(12, UUID(), "HTML Results", "html-resultset-widget"));
  538. self.draggableHistogram = ko.observable(new Widget(12, UUID(), "Histogram", "histogram-widget"));
  539. self.draggableBar = ko.observable(new Widget(12, UUID(), "Bar Chart", "bar-widget"));
  540. self.draggableMap = ko.observable(new Widget(12, UUID(), "Map", "map-widget"));
  541. self.draggableLine = ko.observable(new Widget(12, UUID(), "Line Chart", "line-widget"));
  542. self.draggablePie = ko.observable(new Widget(12, UUID(), "Pie Chart", "pie-widget"));
  543. self.draggableFilter = ko.observable(new Widget(12, UUID(), "Filter Bar", "filter-widget"));
  544. function getWidgets(equalsTo) {
  545. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  546. };
  547. self.availableDraggableResultset = ko.computed(function() {
  548. return getWidgets(function(widget){ return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  549. });
  550. self.availableDraggableFilter = ko.computed(function() {
  551. return getWidgets(function(widget){ return widget.widgetType() == 'filter-widget'; }).length == 0;
  552. });
  553. self.availableDraggableHistogram = ko.computed(function() {
  554. return getWidgets(function(widget){ return widget.widgetType() == 'histogram-widget'; }).length == 0 &&
  555. $.map(self.collection.availableFacetFields(), function(field) { return ['date', 'tdate'].indexOf(field.type()) != -1; });
  556. });
  557. self.availableDraggableChart = ko.computed(function() {
  558. return self.collection.availableFacetFields().length > 0;
  559. });
  560. self.init = function () {
  561. //self.collection.addDynamicFields();
  562. self.isEditing(true);
  563. self.search();
  564. }
  565. self.search = function () {
  566. self.isRetrievingResults(true);
  567. $(".jHueNotify").hide();
  568. // Multi queries
  569. var multiQs = [];
  570. var multiQ = self.query.getMultiq();
  571. if (multiQ != null) {
  572. var facet = {};
  573. var queries = [];
  574. if (multiQ == 'query') {
  575. queries = self.query.qs();
  576. } else {
  577. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  578. queries = facet.filter();
  579. }
  580. multiQs = $.map(queries, function(qdata) {
  581. return $.post("/search/get_timeline", {
  582. collection: ko.mapping.toJSON(self.collection),
  583. query: ko.mapping.toJSON(self.query),
  584. facet: ko.mapping.toJSON(facet),
  585. qdata: ko.mapping.toJSON(qdata),
  586. multiQ: multiQ
  587. }, function (data) {return data});
  588. });
  589. }
  590. $.when.apply($, [
  591. $.post("/search/search", {
  592. collection: ko.mapping.toJSON(self.collection),
  593. query: ko.mapping.toJSON(self.query),
  594. layout: ko.mapping.toJSON(self.columns)
  595. }, function (data) {
  596. self.response(data);
  597. self.results.removeAll();
  598. if (data.error) {
  599. $(document).trigger("error", data.error);
  600. }
  601. else {
  602. if (self.collection.template.isGridLayout()) {
  603. // Table view
  604. $.each(data.response.docs, function (index, item) {
  605. var row = [];
  606. var fields = self.collection.template.fieldsSelected();
  607. // Display selected fields or whole json document
  608. if (fields.length != 0) {
  609. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  610. row.push(item[field]);
  611. });
  612. } else {
  613. row.push(ko.mapping.toJSON(item));
  614. }
  615. var doc = {'id': item[self.collection.idField], 'row': row};
  616. self.results.push(doc);
  617. });
  618. }
  619. else {
  620. // Template view
  621. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  622. $.each(data.response.docs, function (index, item) {
  623. addTemplateFunctions(item);
  624. self.results.push(Mustache.render(_mustacheTmpl, item));
  625. });
  626. }
  627. self.isRetrievingResults(false);
  628. }
  629. })
  630. ].concat(multiQs)
  631. )
  632. .done(function() {
  633. if (arguments[0] instanceof Array) { // If multi queries
  634. var histoFacetId = self.collection.getHistogramFacet().id();
  635. var histoFacet = self.getFacetFromQuery(histoFacetId);
  636. for (var i = 1; i < arguments.length; i++) {
  637. histoFacet.extraSeries.push(arguments[i][0]['series']);
  638. }
  639. self.response.valueHasMutated();
  640. }
  641. })
  642. .fail(function (xhr, textStatus, errorThrown) {
  643. $(document).trigger("error", xhr.responseText);
  644. })
  645. .always(function () {
  646. $('.btn-loading').button('reset');
  647. });
  648. };
  649. self.removeWidget = function (widget_json) {
  650. self.collection.removeFacet(widget_json.id);
  651. self.query.removeFilter(widget_json);
  652. self.search();
  653. }
  654. self.getWidgetById = function (widget_id) {
  655. var _widget = null;
  656. $.each(self.columns(), function (i, col) {
  657. $.each(col.rows(), function (j, row) {
  658. $.each(row.widgets(), function (z, widget) {
  659. if (widget.id() == widget_id){
  660. _widget = widget;
  661. }
  662. });
  663. });
  664. });
  665. return _widget;
  666. }
  667. self.getDocument = function (doc) {
  668. $.post("/search/get_document", {
  669. collection: ko.mapping.toJSON(self.collection),
  670. id: doc.id
  671. },function (data) {
  672. if (data.status == 0) {
  673. alert(ko.mapping.toJSON(data.doc.doc));
  674. }
  675. else if (data.status == 1) {
  676. $(document).trigger("info", data.message);
  677. }
  678. else {
  679. $(document).trigger("error", data.message);
  680. }
  681. }).fail(function (xhr, textStatus, errorThrown) {
  682. $(document).trigger("error", xhr.responseText);
  683. });
  684. };
  685. self.save = function () {
  686. $.post("/search/save", {
  687. collection: ko.mapping.toJSON(self.collection),
  688. layout: ko.mapping.toJSON(self.columns)
  689. },function (data) {
  690. if (data.status == 0) {
  691. self.collection.id = data.id;
  692. $(document).trigger("info", data.message);
  693. }
  694. else {
  695. $(document).trigger("error", data.message);
  696. }
  697. }).fail(function (xhr, textStatus, errorThrown) {
  698. $(document).trigger("error", xhr.responseText);
  699. });
  700. };
  701. };