search.ko.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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 () {
  26. return self.addRow();
  27. };
  28. self.addRow = function (row) {
  29. if (typeof row == "undefined" || row == null) {
  30. row = new Row([]);
  31. }
  32. self.rows.push(row);
  33. return row;
  34. };
  35. }
  36. var Row = function (widgets) {
  37. var self = this;
  38. self.widgets = ko.observableArray(widgets);
  39. self.addWidget = function (widget) {
  40. self.widgets.push(widget);
  41. };
  42. self.move = function (from, to) {
  43. try {
  44. viewModel.columns()[to].addRow(self);
  45. viewModel.columns()[from].rows.remove(self);
  46. }
  47. catch (exception) {
  48. }
  49. }
  50. self.moveDown = function (col, row) {
  51. var _i = col.rows().indexOf(row);
  52. if (_i < col.rows().length - 1) {
  53. var _arr = col.rows();
  54. col.rows.splice(_i, 2, _arr[_i + 1], _arr[_i]);
  55. }
  56. }
  57. self.moveUp = function (col, row) {
  58. var _i = col.rows().indexOf(row);
  59. if (_i >= 1) {
  60. var _arr = col.rows();
  61. col.rows.splice(_i - 1, 2, _arr[_i], _arr[_i - 1]);
  62. }
  63. }
  64. self.remove = function (col, row) {
  65. $.each(self.widgets(), function(i, widget) {
  66. viewModel.removeWidget(widget);
  67. });
  68. col.rows.remove(row);
  69. }
  70. }
  71. // A widget is generic. It has an id that refer to another object (e.g. facet) with the same id.
  72. var Widget = function (size, id, name, widgetType, properties, offset, loading) {
  73. var self = this;
  74. self.size = ko.observable(size).extend({ numeric: 0 });
  75. self.name = ko.observable(name);
  76. self.id = ko.observable(id);
  77. self.widgetType = ko.observable(typeof widgetType != "undefined" && widgetType != null ? widgetType : "empty-widget");
  78. self.properties = ko.observable(typeof properties != "undefined" && properties != null ? properties : {});
  79. self.offset = ko.observable(typeof offset != "undefined" && offset != null ? offset : 0).extend({ numeric: 0 });
  80. self.isLoading = ko.observable(typeof loading != "undefined" && loading != null ? loading : false);
  81. self.klass = ko.computed(function () {
  82. return "card card-widget span" + self.size() + (self.offset() * 1 > 0 ? " offset" + self.offset() : "");
  83. });
  84. self.expand = function () {
  85. self.size(self.size() + 1);
  86. }
  87. self.compress = function () {
  88. self.size(self.size() - 1);
  89. }
  90. self.moveLeft = function () {
  91. self.offset(self.offset() - 1);
  92. }
  93. self.moveRight = function () {
  94. self.offset(self.offset() + 1);
  95. }
  96. self.remove = function (row, widget) {
  97. viewModel.removeWidget(widget);
  98. row.widgets.remove(widget);
  99. }
  100. };
  101. Widget.prototype.clone = function () {
  102. return new Widget(this.size(), UUID(), this.name(), this.widgetType());
  103. };
  104. function fullLayout() {
  105. setLayout([12]);
  106. }
  107. function oneThirdLeftLayout() {
  108. setLayout([2, 10]);
  109. }
  110. function magicLayout(vm) {
  111. loadLayout(vm, vm.initial.layout);
  112. }
  113. function setLayout(colSizes) {
  114. // Save previous widgets
  115. var _allRows = [];
  116. $(viewModel.columns()).each(function (cnt, col) {
  117. var _tRows = [];
  118. $(col.rows()).each(function (icnt, row) {
  119. if (row.widgets().length > 0) {
  120. _tRows.push(row);
  121. }
  122. });
  123. _allRows = _allRows.concat(_tRows);
  124. });
  125. var _cols = [];
  126. var _highestCol = {
  127. idx: -1,
  128. size: -1
  129. };
  130. $(colSizes).each(function (cnt, size) {
  131. _cols.push(new Column(size, []));
  132. if (size > _highestCol.size) {
  133. _highestCol.idx = cnt;
  134. _highestCol.size = size;
  135. }
  136. });
  137. if (_allRows.length > 0 && _highestCol.idx > -1) {
  138. _cols[_highestCol.idx].rows(_allRows);
  139. }
  140. $(_cols).each(function (cnt, col) {
  141. if (col.rows().length == 0) {
  142. col.rows([new Row([])]);
  143. }
  144. });
  145. viewModel.columns(_cols);
  146. }
  147. function loadLayout(viewModel, json_layout) {
  148. var _columns = [];
  149. $(json_layout).each(function (cnt, json_col) {
  150. var _rows = [];
  151. $(json_col.rows).each(function (rcnt, json_row) {
  152. var row = new Row();
  153. $(json_row.widgets).each(function (wcnt, widget) {
  154. row.addWidget(new Widget(widget.size, widget.id, widget.name, widget.widgetType, widget.properties, widget.offset, true));
  155. });
  156. _rows.push(row);
  157. });
  158. var column = new Column(json_col.size, _rows);
  159. _columns = _columns.concat(column);
  160. });
  161. viewModel.columns(_columns);
  162. }
  163. // End dashboard lib
  164. var Query = function (vm, query) {
  165. var self = this;
  166. self.qs = ko.mapping.fromJS(query.qs);
  167. self.fqs = ko.mapping.fromJS(query.fqs);
  168. self.start = ko.mapping.fromJS(query.start);
  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) {
  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. self.paginate = function (direction) {
  280. if (direction == 'next') {
  281. self.start(self.start() + vm.collection.template.rows() * 1.0);
  282. } else {
  283. self.start(self.start() - vm.collection.template.rows() * 1.0);
  284. }
  285. vm.search();
  286. };
  287. };
  288. var Collection = function (vm, collection) {
  289. var self = this;
  290. self.id = collection.id;
  291. self.name = ko.mapping.fromJS(collection.name);
  292. self.label = ko.mapping.fromJS(collection.label);
  293. self.enabled = ko.mapping.fromJS(collection.enabled);
  294. self.idField = ko.observable(collection.idField);
  295. self.template = ko.mapping.fromJS(collection.template);
  296. self.template.fieldsSelected.subscribe(function () {
  297. vm.search();
  298. });
  299. self.template.template.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  300. self.template.template.subscribe(function () {
  301. vm.search();
  302. });
  303. self.template.isGridLayout.subscribe(function () {
  304. vm.search();
  305. });
  306. self.template.selectedVisualField = ko.observable();
  307. self.template.selectedVisualFunction = ko.observable();
  308. self.template.selectedVisualFunction.subscribe(function (newValue) {
  309. var _vf = $("#visualFunctions");
  310. _vf.siblings(".muted").text(_vf.find(":selected").attr("title"));
  311. });
  312. self.template.selectedSourceField = ko.observable();
  313. self.template.selectedSourceFunction = ko.observable();
  314. self.template.selectedSourceFunction.subscribe(function (newValue) {
  315. var _sf = $("#sourceFunctions");
  316. _sf.siblings(".muted").text(_sf.find(":selected").attr("title"));
  317. });
  318. self.template.addFieldToVisual = function () {
  319. $(document).trigger("addFieldToVisual", self.template.selectedVisualField());
  320. };
  321. self.template.addFunctionToVisual = function () {
  322. $(document).trigger("addFunctionToVisual", self.template.selectedVisualFunction());
  323. };
  324. self.template.addFieldToSource = function () {
  325. $(document).trigger("addFieldToSource", self.template.selectedSourceField());
  326. };
  327. self.template.addFunctionToSource = function () {
  328. $(document).trigger("addFunctionToSource", self.template.selectedSourceFunction());
  329. };
  330. self.facets = ko.mapping.fromJS(collection.facets);
  331. $.each(self.facets(), function (index, facet) {
  332. facet.field.subscribe(function () {
  333. vm.search();
  334. });
  335. });
  336. self.template.rows.subscribe(function(){
  337. vm.search();
  338. });
  339. self.template.rows.extend({rateLimit: {timeout: 1500, method: "notifyWhenChangesStop"}});
  340. self.fields = ko.mapping.fromJS(collection.fields);
  341. self.availableFacetFields = ko.computed(function() {
  342. var facetFieldNames = $.map(self.facets(), function(facet) {
  343. return facet.field(); //filter out text_general
  344. });
  345. return $.grep(self.fields(), function(field) {
  346. return facetFieldNames.indexOf(field.name()) == -1;
  347. });
  348. });
  349. self.selectedDocument = ko.observable({});
  350. self.addFacet = function (facet_json) {
  351. self.removeFacet(function(){return facet_json.widget_id});
  352. $.post("/search/template/new_facet", {
  353. "collection": ko.mapping.toJSON(self),
  354. "id": facet_json.widget_id,
  355. "label": facet_json.name,
  356. "field": facet_json.name,
  357. "widget_type": facet_json.widgetType
  358. }, function (data) {
  359. if (data.status == 0) {
  360. var facet = ko.mapping.fromJS(data.facet);
  361. facet.field.subscribe(function () {
  362. vm.search();
  363. });
  364. self.facets.push(facet);
  365. vm.search();
  366. } else {
  367. $(document).trigger("error", data.message);
  368. }
  369. }).fail(function (xhr, textStatus, errorThrown) {});
  370. };
  371. self.removeFacet = function (widget_id) {
  372. $.each(self.facets(), function (index, facet) {
  373. if (facet.id() == widget_id()) {
  374. self.facets.remove(facet);
  375. return false;
  376. }
  377. });
  378. }
  379. self.getFacetById = function (facet_id) {
  380. var _facet = null;
  381. $.each(self.facets(), function (index, facet) {
  382. if (facet.id() == facet_id) {
  383. _facet = facet;
  384. return false;
  385. }
  386. });
  387. return _facet;
  388. }
  389. self.getFacetByType = function (facetType) {
  390. var _facet = null;
  391. $.each(self.facets(), function (index, facet) {
  392. if (facet.widgetType() == facetType) {
  393. _facet = facet;
  394. return false;
  395. }
  396. });
  397. return _facet;
  398. }
  399. self.getHistogramFacet = function () { // might remove when list of available widgets
  400. return self.getFacetByType('histogram-widget');
  401. }
  402. self.template.fields = ko.computed(function () {
  403. var _fields = [];
  404. $.each(self.template.fieldsAttributes(), function (index, field) {
  405. var position = self.template.fieldsSelected.indexOf(field.name());
  406. if (position != -1) {
  407. _fields[position] = field;
  408. }
  409. });
  410. return _fields;
  411. });
  412. self.getTemplateField = function (name) {
  413. var _field = null;
  414. $.each(self.template.fields(), function (index, field) {
  415. if (field.name() == name) {
  416. _field = field;
  417. return false;
  418. }
  419. });
  420. return _field;
  421. };
  422. self.template.fieldsModalFilter = ko.observable(); // For UI
  423. self.template.fieldsModalType = ko.observable(""); // For UI
  424. self.template.fieldsAttributesFilter = ko.observable(""); // For UI
  425. self.template.filteredModalFields = ko.observableArray();
  426. self.template.filteredAttributeFields = ko.computed(function() {
  427. var _fields = [];
  428. $.each(self.template.fieldsAttributes(), function (index, field) {
  429. if (self.template.fieldsAttributesFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsAttributesFilter().toLowerCase()) > -1){
  430. _fields.push(field);
  431. }
  432. });
  433. return _fields;
  434. });
  435. self.template.availableWidgetFields = ko.computed(function() {
  436. return self.template.fieldsModalType() == 'histogram-widget'? vm.availableDateFields() : self.availableFacetFields();
  437. });
  438. self.template.availableWidgetFieldsNames = ko.computed(function() {
  439. return $.map(self.template.availableWidgetFields(), function(field){
  440. return field.name();
  441. });
  442. });
  443. self.template.fieldsModalFilter.subscribe(function(value) {
  444. var _fields = [];
  445. var _availableFields = self.template.availableWidgetFields();
  446. $.each(_availableFields, function (index, field) {
  447. if (self.template.fieldsModalFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  448. _fields.push(field);
  449. }
  450. });
  451. self.template.filteredModalFields(_fields);
  452. });
  453. self.switchCollection = function() {
  454. $.post("/search/get_collection/", {
  455. name: self.name()
  456. }, function (data) {
  457. if (data.status == 0) {
  458. self.idField(data.collection.collection.idField);
  459. self.template.template(data.collection.collection.template.template);
  460. self.template.fieldsAttributes.removeAll();
  461. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  462. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  463. });
  464. self.fields.removeAll();
  465. $.each(data.collection.collection.fields, function(index, field) {
  466. self.fields.push(ko.mapping.fromJS(field));
  467. });
  468. }
  469. }).fail(function (xhr, textStatus, errorThrown) {});
  470. };
  471. function diff(A, B) {
  472. return A.filter(function (a) {
  473. return B.indexOf(a) == -1;
  474. });
  475. }
  476. function syncArray(currentObservable, newJson) {
  477. // Get names of fields
  478. var _currentFieldsNames = $.map(currentObservable(), function(field){ return field.name(); });
  479. var _newFieldsNames = $.map(newJson, function(field){ return field.name; });
  480. var _toDelete = diff(_currentFieldsNames, _newFieldsNames);
  481. var _toAdd = diff(_newFieldsNames, _currentFieldsNames);
  482. // Deleted fields
  483. $.each(currentObservable(), function(index, field) {
  484. if (_toDelete.indexOf(field.name()) != -1) {
  485. currentObservable.remove(field);
  486. }
  487. });
  488. // New fields
  489. $.each(newJson, function(index, field) {
  490. if (_toAdd.indexOf(field.name) != -1) {
  491. currentObservable.push(ko.mapping.fromJS(field));
  492. }
  493. });
  494. }
  495. self.syncFields = function() {
  496. $.post("/search/get_collection/", {
  497. name: self.name()
  498. }, function (data) {
  499. if (data.status == 0) {
  500. self.idField(data.collection.collection.idField); // template?
  501. syncArray(self.template.fieldsAttributes, data.collection.collection.template.fieldsAttributes);
  502. syncArray(self.fields, data.collection.collection.fields);
  503. }
  504. }).fail(function (xhr, textStatus, errorThrown) {});
  505. };
  506. // syncDynamicFields
  507. self.addDynamicFields = function () { // + Adding merge smartly if schema updated
  508. $.post("/search/index/" + self.id + "/fields/dynamic", {
  509. }, function (data) {
  510. if (data.status == 0) {
  511. $.each(data.dynamic_fields, function (index, field) {
  512. if (self.fields.indexOf(field) == -1) {
  513. self.fields.push(field);
  514. }
  515. });
  516. }
  517. }).fail(function (xhr, textStatus, errorThrown) {});
  518. };
  519. self.toggleSortColumnGridLayout = function (template_field) {
  520. if (! template_field.sort.direction()) {
  521. template_field.sort.direction('desc');
  522. } else if (template_field.sort.direction() == 'desc') {
  523. template_field.sort.direction('asc');
  524. } else {
  525. template_field.sort.direction(null);
  526. }
  527. vm.search();
  528. };
  529. self.toggleSortFacet = function (facet_field, event) {
  530. if (facet_field.properties.sort() == 'desc') {
  531. facet_field.properties.sort('asc');
  532. } else {
  533. facet_field.properties.sort('desc');
  534. }
  535. $(event.target).button('loading');
  536. vm.search();
  537. };
  538. self.toggleRangeFacet = function (facet_field, event) {
  539. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  540. if (facet_field.type() == 'field') {
  541. facet_field.type('range');
  542. } else if (facet_field.type() == 'range') {
  543. facet_field.type('field')
  544. }
  545. $(event.target).button('loading');
  546. vm.search();
  547. };
  548. self.selectTimelineFacet = function (data) { // alert(ko.mapping.toJSON(facet));
  549. var facet = self.getFacetById(data.widget_id);
  550. facet.properties.start(data.from);
  551. facet.properties.end(data.to);
  552. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  553. $.ajax({
  554. type: "POST",
  555. url: "/search/get_range_facet",
  556. data: {
  557. collection: ko.mapping.toJSON(self),
  558. facet: ko.mapping.toJSON(facet),
  559. action: 'select'
  560. },
  561. success: function (data) {
  562. if (data.status == 0) {
  563. facet.properties.gap(data.properties.gap);
  564. }
  565. },
  566. async: false
  567. });
  568. vm.search();
  569. }
  570. self.timeLineZoom = function (facet_json) {
  571. var facet = self.getFacetById(facet_json.id);
  572. facet.properties.start(facet.from);
  573. facet.properties.end(facet.to);
  574. $.ajax({
  575. type: "POST",
  576. url: "/search/get_range_facet",
  577. data: {
  578. collection: ko.mapping.toJSON(self),
  579. facet: ko.mapping.toJSON(facet),
  580. action: "zoom_out"
  581. },
  582. success: function (data) {
  583. if (data.status == 0) {
  584. facet.properties.start(data.properties.start);
  585. facet.properties.end(data.properties.end);
  586. facet.properties.gap(data.properties.gap);
  587. }
  588. },
  589. async: false
  590. });
  591. vm.search();
  592. }
  593. self.translateSelectedField = function (index, direction) {
  594. var array = self.template.fieldsSelected();
  595. if (direction == 'left') {
  596. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  597. } else {
  598. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  599. }
  600. vm.search();
  601. };
  602. self.upDownFacetLimit = function (facet_id, direction) {
  603. var facet = self.getFacetById(facet_id);
  604. if (facet.properties.prevLimit == undefined) {
  605. facet.properties.prevLimit = facet.properties.limit();
  606. }
  607. if (direction == 'up') {
  608. facet.properties.limit(facet.properties.limit() + 10);
  609. } else {
  610. facet.properties.limit(facet.properties.limit() - 10);
  611. }
  612. vm.search();
  613. };
  614. };
  615. var NewTemplate = function (vm, initial) {
  616. var self = this;
  617. self.collections = ko.mapping.fromJS(initial.collections);
  618. self.layout = initial.layout;
  619. };
  620. var DATE_TYPE = ['date', 'tdate'];
  621. var SearchViewModel = function (collection_json, query_json, initial_json) {
  622. var self = this;
  623. // Models
  624. self.collection = new Collection(self, collection_json.collection);
  625. self.query = new Query(self, query_json);
  626. self.initial = new NewTemplate(self, initial_json);
  627. if (initial_json.collections) {
  628. self.collection.name.subscribe(function (newValue) {
  629. self.collection.label(newValue);
  630. self.collection.switchCollection();
  631. self.changeCollection(false);
  632. self.search();
  633. });
  634. }
  635. // UI
  636. self.response = ko.observable({});
  637. self.results = ko.observableArray([]);
  638. self.norm_facets = ko.computed(function () {
  639. return self.response().normalized_facets;
  640. });
  641. self.getFacetFromQuery = function (facet_id) {
  642. var _facet = null;
  643. if (self.norm_facets() !== undefined) {
  644. $.each(self.norm_facets(), function (index, norm_facet) {
  645. if (norm_facet.id == facet_id) {
  646. _facet = norm_facet;
  647. }
  648. });
  649. }
  650. return _facet;
  651. };
  652. self.changeCollection = ko.observable(false);
  653. self.toggledGridlayoutResultChevron = ko.observable(false);
  654. self.enableGridlayoutResultChevron = function() {
  655. self.toggledGridlayoutResultChevron(true);
  656. };
  657. self.disableGridlayoutResultChevron = function() {
  658. self.toggledGridlayoutResultChevron(false);
  659. };
  660. self.previewColumns = ko.observable("");
  661. self.columns = ko.observable([]);
  662. loadLayout(self, collection_json.layout);
  663. self.isEditing = ko.observable(false);
  664. self.toggleEditing = function () {
  665. self.isEditing(!self.isEditing());
  666. };
  667. self.isRetrievingResults = ko.observable(false);
  668. self.draggableHit = ko.observable(new Widget(12, UUID(), "Hit Count", "hit-widget"));
  669. self.draggableFacet = ko.observable(new Widget(12, UUID(), "Facet", "facet-widget"));
  670. self.draggableResultset = ko.observable(new Widget(12, UUID(), "Grid Results", "resultset-widget"));
  671. self.draggableHtmlResultset = ko.observable(new Widget(12, UUID(), "HTML Results", "html-resultset-widget"));
  672. self.draggableHistogram = ko.observable(new Widget(12, UUID(), "Histogram", "histogram-widget"));
  673. self.draggableBar = ko.observable(new Widget(12, UUID(), "Bar Chart", "bar-widget"));
  674. self.draggableMap = ko.observable(new Widget(12, UUID(), "Map", "map-widget"));
  675. self.draggableLine = ko.observable(new Widget(12, UUID(), "Line Chart", "line-widget"));
  676. self.draggablePie = ko.observable(new Widget(12, UUID(), "Pie Chart", "pie-widget"));
  677. self.draggableFilter = ko.observable(new Widget(12, UUID(), "Filter Bar", "filter-widget"));
  678. self.availableDateFields = ko.computed(function() {
  679. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPE.indexOf(field.type()) != -1; });
  680. });
  681. function getWidgets(equalsTo) {
  682. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  683. };
  684. self.availableDraggableResultset = ko.computed(function() {
  685. return getWidgets(function(widget){ return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  686. });
  687. self.availableDraggableFilter = ko.computed(function() {
  688. return getWidgets(function(widget){ return widget.widgetType() == 'filter-widget'; }).length == 0;
  689. });
  690. self.availableDraggableHistogram = ko.computed(function() {
  691. return getWidgets(function(widget){ return widget.widgetType() == 'histogram-widget'; }).length == 0 &&
  692. self.availableDateFields().length > 0;
  693. });
  694. self.availableDraggableChart = ko.computed(function() {
  695. return self.collection.availableFacetFields().length > 0;
  696. });
  697. self.init = function (callback) {
  698. //self.collection.addDynamicFields();
  699. self.collection.syncFields();
  700. self.isEditing(true);
  701. self.search(callback);
  702. }
  703. self.searchBtn = function () {
  704. self.query.start(0);
  705. self.search();
  706. };
  707. self.search = function (callback) {
  708. self.isRetrievingResults(true);
  709. $(".jHueNotify").hide();
  710. // Multi queries
  711. var multiQs = [];
  712. var multiQ = self.query.getMultiq();
  713. if (multiQ != null) {
  714. var facet = {};
  715. var queries = [];
  716. if (multiQ == 'query') {
  717. queries = self.query.qs();
  718. } else {
  719. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  720. queries = facet.filter();
  721. }
  722. multiQs = $.map(queries, function(qdata) {
  723. return $.post("/search/get_timeline", {
  724. collection: ko.mapping.toJSON(self.collection),
  725. query: ko.mapping.toJSON(self.query),
  726. facet: ko.mapping.toJSON(facet),
  727. qdata: ko.mapping.toJSON(qdata),
  728. multiQ: multiQ
  729. }, function (data) {return data});
  730. });
  731. }
  732. $.when.apply($, [
  733. $.post("/search/search", {
  734. collection: ko.mapping.toJSON(self.collection),
  735. query: ko.mapping.toJSON(self.query),
  736. layout: ko.mapping.toJSON(self.columns)
  737. }, function (data) {
  738. if (typeof callback != undefined && callback != null){
  739. callback(data);
  740. }
  741. self.response(data);
  742. self.results.removeAll();
  743. if (data.error) {
  744. $(document).trigger("error", data.error);
  745. }
  746. else {
  747. if (self.collection.template.isGridLayout()) {
  748. // Table view
  749. $.each(data.response.docs, function (index, item) {
  750. var row = [];
  751. var fields = self.collection.template.fieldsSelected();
  752. // Display selected fields or whole json document
  753. if (fields.length != 0) {
  754. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  755. row.push(item[field]);
  756. });
  757. } else {
  758. row.push(ko.mapping.toJSON(item));
  759. }
  760. var doc = {'id': item[self.collection.idField()], 'row': row};
  761. self.results.push(doc);
  762. });
  763. }
  764. else {
  765. // Template view
  766. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  767. $.each(data.response.docs, function (index, item) {
  768. for (var prop in item) {
  769. if (item.hasOwnProperty(prop)) {
  770. item[prop] = $("<span>").html(item[prop]).text();
  771. }
  772. }
  773. // fix the fields that contain dots in the name
  774. addTemplateFunctions(item);
  775. self.results.push(Mustache.render(_mustacheTmpl, item));
  776. });
  777. }
  778. self.isRetrievingResults(false);
  779. }
  780. })
  781. ].concat(multiQs)
  782. )
  783. .done(function() {
  784. if (arguments[0] instanceof Array) { // If multi queries
  785. var histoFacetId = self.collection.getHistogramFacet().id();
  786. var histoFacet = self.getFacetFromQuery(histoFacetId);
  787. for (var i = 1; i < arguments.length; i++) {
  788. histoFacet.extraSeries.push(arguments[i][0]['series']);
  789. }
  790. self.response.valueHasMutated();
  791. }
  792. })
  793. .fail(function (xhr, textStatus, errorThrown) {
  794. $(document).trigger("error", xhr.responseText);
  795. })
  796. .always(function () {
  797. $('.btn-loading').button('reset');
  798. });
  799. };
  800. self.removeWidget = function (widget_json) {
  801. self.collection.removeFacet(widget_json.id);
  802. self.query.removeFilter(widget_json);
  803. self.removeWidgetById(widget_json.id());
  804. self.search();
  805. }
  806. self.getWidgetById = function (widget_id) {
  807. var _widget = null;
  808. $.each(self.columns(), function (i, col) {
  809. $.each(col.rows(), function (j, row) {
  810. $.each(row.widgets(), function (z, widget) {
  811. if (widget.id() == widget_id){
  812. _widget = widget;
  813. }
  814. });
  815. });
  816. });
  817. return _widget;
  818. }
  819. self.removeWidgetById = function (widget_id) {
  820. $.each(self.columns(), function (i, col) {
  821. $.each(col.rows(), function (j, row) {
  822. $.each(row.widgets(), function (z, widget) {
  823. if (widget.id() == widget_id){
  824. row.widgets.remove(widget);
  825. }
  826. });
  827. });
  828. });
  829. }
  830. self.getDocument = function (doc) {
  831. $.post("/search/get_document", {
  832. collection: ko.mapping.toJSON(self.collection),
  833. id: doc.id
  834. },function (data) {
  835. if (data.status == 0) {
  836. $(document).trigger("showDoc", data.doc.doc);
  837. }
  838. else if (data.status == 1) {
  839. $(document).trigger("info", data.message);
  840. }
  841. else {
  842. $(document).trigger("error", data.message);
  843. }
  844. }).fail(function (xhr, textStatus, errorThrown) {
  845. $(document).trigger("error", xhr.responseText);
  846. });
  847. };
  848. self.save = function () {
  849. $.post("/search/save", {
  850. collection: ko.mapping.toJSON(self.collection),
  851. layout: ko.mapping.toJSON(self.columns)
  852. },function (data) {
  853. if (data.status == 0) {
  854. self.collection.id = data.id;
  855. $(document).trigger("info", data.message);
  856. window.location.hash = '#collection=' + data.id;
  857. }
  858. else {
  859. $(document).trigger("error", data.message);
  860. }
  861. }).fail(function (xhr, textStatus, errorThrown) {
  862. $(document).trigger("error", xhr.responseText);
  863. });
  864. };
  865. };