search.ko.js 31 KB

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