search.ko.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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.updateCollection = 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. self.syncFields = function() {
  472. $.post("/search/get_collection/", {
  473. name: self.name()
  474. }, function (data) {
  475. if (data.status == 0) {
  476. self.idField(data.collection.collection.idField);
  477. var _newNames = $.map(data.collection.collection.template.fieldsAttributes, function(field){ return field.name; });
  478. var _newFields = [];
  479. self.template.fieldsAttributes.removeAll();
  480. $.each(self.template.fieldsAttributes(), function(index, field) {//alert(ko.mapping.toJSON(field));
  481. if (_newNames.indexOf(field.name()) == -1) {
  482. self.template.fieldsAttributes.remove(field);
  483. } else {
  484. // _newFields.push(ko.mapping.fromJS(field));
  485. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  486. }
  487. });
  488. self.fields.removeAll();
  489. alert('aa');
  490. /**ko.utils.arrayForEach(differences, function(difference) {
  491. if (difference.status === "added") {
  492. self.template.fieldsAttribute.push()
  493. } else if (difference.status === "deleted") {
  494. results.push(difference.value);
  495. }
  496. });
  497. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  498. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  499. });
  500. self.fields.removeAll();
  501. $.each(data.collection.collection.fields, function(index, field) {
  502. self.fields.push(ko.mapping.fromJS(field));
  503. });
  504. self.template.fieldsAttributesFilter.valueHasMutated();*/
  505. }
  506. }).fail(function (xhr, textStatus, errorThrown) {});
  507. };
  508. // syncDynamicFields
  509. self.addDynamicFields = function () { // + Adding merge smartly if schema updated
  510. $.post("/search/index/" + self.id + "/fields/dynamic", {
  511. }, function (data) {
  512. if (data.status == 0) {
  513. $.each(data.dynamic_fields, function (index, field) {
  514. if (self.fields.indexOf(field) == -1) {
  515. self.fields.push(field);
  516. }
  517. });
  518. }
  519. }).fail(function (xhr, textStatus, errorThrown) {});
  520. };
  521. self.toggleSortColumnGridLayout = function (template_field) {
  522. if (! template_field.sort.direction()) {
  523. template_field.sort.direction('desc');
  524. } else if (template_field.sort.direction() == 'desc') {
  525. template_field.sort.direction('asc');
  526. } else {
  527. template_field.sort.direction(null);
  528. }
  529. vm.search();
  530. };
  531. self.toggleSortFacet = function (facet_field, event) {
  532. if (facet_field.properties.sort() == 'desc') {
  533. facet_field.properties.sort('asc');
  534. } else {
  535. facet_field.properties.sort('desc');
  536. }
  537. $(event.target).button('loading');
  538. vm.search();
  539. };
  540. self.toggleRangeFacet = function (facet_field, event) {
  541. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  542. if (facet_field.type() == 'field') {
  543. facet_field.type('range');
  544. } else if (facet_field.type() == 'range') {
  545. facet_field.type('field')
  546. }
  547. $(event.target).button('loading');
  548. vm.search();
  549. };
  550. self.selectTimelineFacet = function (data) { // alert(ko.mapping.toJSON(facet));
  551. var facet = self.getFacetById(data.widget_id);
  552. facet.properties.start(data.from);
  553. facet.properties.end(data.to);
  554. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  555. $.ajax({
  556. type: "POST",
  557. url: "/search/get_range_facet",
  558. data: {
  559. collection: ko.mapping.toJSON(self),
  560. facet: ko.mapping.toJSON(facet),
  561. action: 'select'
  562. },
  563. success: function (data) {
  564. if (data.status == 0) {
  565. facet.properties.gap(data.properties.gap);
  566. }
  567. },
  568. async: false
  569. });
  570. vm.search();
  571. }
  572. self.timeLineZoom = function (facet_json) {
  573. var facet = self.getFacetById(facet_json.id);
  574. facet.properties.start(facet.from);
  575. facet.properties.end(facet.to);
  576. $.ajax({
  577. type: "POST",
  578. url: "/search/get_range_facet",
  579. data: {
  580. collection: ko.mapping.toJSON(self),
  581. facet: ko.mapping.toJSON(facet),
  582. action: "zoom_out"
  583. },
  584. success: function (data) {
  585. if (data.status == 0) {
  586. facet.properties.start(data.properties.start);
  587. facet.properties.end(data.properties.end);
  588. facet.properties.gap(data.properties.gap);
  589. }
  590. },
  591. async: false
  592. });
  593. vm.search();
  594. }
  595. self.translateSelectedField = function (index, direction) {
  596. var array = self.template.fieldsSelected();
  597. if (direction == 'left') {
  598. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  599. } else {
  600. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  601. }
  602. vm.search();
  603. };
  604. self.upDownFacetLimit = function (facet_id, direction) {
  605. var facet = self.getFacetById(facet_id);
  606. if (facet.properties.prevLimit == undefined) {
  607. facet.properties.prevLimit = facet.properties.limit();
  608. }
  609. if (direction == 'up') {
  610. facet.properties.limit(facet.properties.limit() + 10);
  611. } else {
  612. facet.properties.limit(facet.properties.limit() - 10);
  613. }
  614. vm.search();
  615. };
  616. };
  617. var NewTemplate = function (vm, initial) {
  618. var self = this;
  619. self.collections = ko.mapping.fromJS(initial.collections);
  620. self.layout = initial.layout;
  621. };
  622. var DATE_TYPE = ['date', 'tdate'];
  623. var SearchViewModel = function (collection_json, query_json, initial_json) {
  624. var self = this;
  625. // Models
  626. self.collection = new Collection(self, collection_json.collection);
  627. self.query = new Query(self, query_json);
  628. self.initial = new NewTemplate(self, initial_json);
  629. if (initial_json.collections) {
  630. self.collection.name.subscribe(function (newValue) {
  631. self.collection.label(newValue);
  632. self.collection.updateCollection();
  633. self.changeCollection(false);
  634. self.search();
  635. });
  636. }
  637. // UI
  638. self.response = ko.observable({});
  639. self.results = ko.observableArray([]);
  640. self.norm_facets = ko.computed(function () {
  641. return self.response().normalized_facets;
  642. });
  643. self.getFacetFromQuery = function (facet_id) {
  644. var _facet = null;
  645. if (self.norm_facets() !== undefined) {
  646. $.each(self.norm_facets(), function (index, norm_facet) {
  647. if (norm_facet.id == facet_id) {
  648. _facet = norm_facet;
  649. }
  650. });
  651. }
  652. return _facet;
  653. };
  654. self.changeCollection = ko.observable(false);
  655. self.toggledGridlayoutResultChevron = ko.observable(false);
  656. self.enableGridlayoutResultChevron = function() {
  657. self.toggledGridlayoutResultChevron(true);
  658. };
  659. self.disableGridlayoutResultChevron = function() {
  660. self.toggledGridlayoutResultChevron(false);
  661. };
  662. self.previewColumns = ko.observable("");
  663. self.columns = ko.observable([]);
  664. loadLayout(self, collection_json.layout);
  665. self.isEditing = ko.observable(false);
  666. self.toggleEditing = function () {
  667. self.isEditing(!self.isEditing());
  668. };
  669. self.isRetrievingResults = ko.observable(false);
  670. self.draggableHit = ko.observable(new Widget(12, UUID(), "Hit Count", "hit-widget"));
  671. self.draggableFacet = ko.observable(new Widget(12, UUID(), "Facet", "facet-widget"));
  672. self.draggableResultset = ko.observable(new Widget(12, UUID(), "Grid Results", "resultset-widget"));
  673. self.draggableHtmlResultset = ko.observable(new Widget(12, UUID(), "HTML Results", "html-resultset-widget"));
  674. self.draggableHistogram = ko.observable(new Widget(12, UUID(), "Histogram", "histogram-widget"));
  675. self.draggableBar = ko.observable(new Widget(12, UUID(), "Bar Chart", "bar-widget"));
  676. self.draggableMap = ko.observable(new Widget(12, UUID(), "Map", "map-widget"));
  677. self.draggableLine = ko.observable(new Widget(12, UUID(), "Line Chart", "line-widget"));
  678. self.draggablePie = ko.observable(new Widget(12, UUID(), "Pie Chart", "pie-widget"));
  679. self.draggableFilter = ko.observable(new Widget(12, UUID(), "Filter Bar", "filter-widget"));
  680. self.availableDateFields = ko.computed(function() {
  681. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPE.indexOf(field.type()) != -1; });
  682. });
  683. function getWidgets(equalsTo) {
  684. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  685. };
  686. self.availableDraggableResultset = ko.computed(function() {
  687. return getWidgets(function(widget){ return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  688. });
  689. self.availableDraggableFilter = ko.computed(function() {
  690. return getWidgets(function(widget){ return widget.widgetType() == 'filter-widget'; }).length == 0;
  691. });
  692. self.availableDraggableHistogram = ko.computed(function() {
  693. return getWidgets(function(widget){ return widget.widgetType() == 'histogram-widget'; }).length == 0 &&
  694. self.availableDateFields().length > 0;
  695. });
  696. self.availableDraggableChart = ko.computed(function() {
  697. return self.collection.availableFacetFields().length > 0;
  698. });
  699. self.init = function (callback) {
  700. //self.collection.addDynamicFields();
  701. //self.collection.syncFields();
  702. self.isEditing(true);
  703. self.search(callback);
  704. }
  705. self.searchBtn = function () {
  706. self.query.start(0);
  707. self.search();
  708. };
  709. self.search = function (callback) {
  710. self.isRetrievingResults(true);
  711. $(".jHueNotify").hide();
  712. // Multi queries
  713. var multiQs = [];
  714. var multiQ = self.query.getMultiq();
  715. if (multiQ != null) {
  716. var facet = {};
  717. var queries = [];
  718. if (multiQ == 'query') {
  719. queries = self.query.qs();
  720. } else {
  721. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  722. queries = facet.filter();
  723. }
  724. multiQs = $.map(queries, function(qdata) {
  725. return $.post("/search/get_timeline", {
  726. collection: ko.mapping.toJSON(self.collection),
  727. query: ko.mapping.toJSON(self.query),
  728. facet: ko.mapping.toJSON(facet),
  729. qdata: ko.mapping.toJSON(qdata),
  730. multiQ: multiQ
  731. }, function (data) {return data});
  732. });
  733. }
  734. $.when.apply($, [
  735. $.post("/search/search", {
  736. collection: ko.mapping.toJSON(self.collection),
  737. query: ko.mapping.toJSON(self.query),
  738. layout: ko.mapping.toJSON(self.columns)
  739. }, function (data) {
  740. if (typeof callback != undefined && callback != null){
  741. callback(data);
  742. }
  743. self.response(data);
  744. self.results.removeAll();
  745. if (data.error) {
  746. $(document).trigger("error", data.error);
  747. }
  748. else {
  749. if (self.collection.template.isGridLayout()) {
  750. // Table view
  751. $.each(data.response.docs, function (index, item) {
  752. var row = [];
  753. var fields = self.collection.template.fieldsSelected();
  754. // Display selected fields or whole json document
  755. if (fields.length != 0) {
  756. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  757. row.push(item[field]);
  758. });
  759. } else {
  760. row.push(ko.mapping.toJSON(item));
  761. }
  762. var doc = {'id': item[self.collection.idField()], 'row': row};
  763. self.results.push(doc);
  764. });
  765. }
  766. else {
  767. // Template view
  768. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  769. $.each(data.response.docs, function (index, item) {
  770. for (var prop in item) {
  771. if (item.hasOwnProperty(prop)) {
  772. item[prop] = $("<span>").html(item[prop]).text();
  773. }
  774. }
  775. // fix the fields that contain dots in the name
  776. addTemplateFunctions(item);
  777. self.results.push(Mustache.render(_mustacheTmpl, item));
  778. });
  779. }
  780. self.isRetrievingResults(false);
  781. }
  782. })
  783. ].concat(multiQs)
  784. )
  785. .done(function() {
  786. if (arguments[0] instanceof Array) { // If multi queries
  787. var histoFacetId = self.collection.getHistogramFacet().id();
  788. var histoFacet = self.getFacetFromQuery(histoFacetId);
  789. for (var i = 1; i < arguments.length; i++) {
  790. histoFacet.extraSeries.push(arguments[i][0]['series']);
  791. }
  792. self.response.valueHasMutated();
  793. }
  794. })
  795. .fail(function (xhr, textStatus, errorThrown) {
  796. $(document).trigger("error", xhr.responseText);
  797. })
  798. .always(function () {
  799. $('.btn-loading').button('reset');
  800. });
  801. };
  802. self.removeWidget = function (widget_json) {
  803. self.collection.removeFacet(widget_json.id);
  804. self.query.removeFilter(widget_json);
  805. self.removeWidgetById(widget_json.id());
  806. self.search();
  807. }
  808. self.getWidgetById = function (widget_id) {
  809. var _widget = null;
  810. $.each(self.columns(), function (i, col) {
  811. $.each(col.rows(), function (j, row) {
  812. $.each(row.widgets(), function (z, widget) {
  813. if (widget.id() == widget_id){
  814. _widget = widget;
  815. }
  816. });
  817. });
  818. });
  819. return _widget;
  820. }
  821. self.removeWidgetById = function (widget_id) {
  822. $.each(self.columns(), function (i, col) {
  823. $.each(col.rows(), function (j, row) {
  824. $.each(row.widgets(), function (z, widget) {
  825. if (widget.id() == widget_id){
  826. row.widgets.remove(widget);
  827. }
  828. });
  829. });
  830. });
  831. }
  832. self.getDocument = function (doc) {
  833. $.post("/search/get_document", {
  834. collection: ko.mapping.toJSON(self.collection),
  835. id: doc.id
  836. },function (data) {
  837. if (data.status == 0) {
  838. $(document).trigger("showDoc", data.doc.doc);
  839. }
  840. else if (data.status == 1) {
  841. $(document).trigger("info", data.message);
  842. }
  843. else {
  844. $(document).trigger("error", data.message);
  845. }
  846. }).fail(function (xhr, textStatus, errorThrown) {
  847. $(document).trigger("error", xhr.responseText);
  848. });
  849. };
  850. self.save = function () {
  851. $.post("/search/save", {
  852. collection: ko.mapping.toJSON(self.collection),
  853. layout: ko.mapping.toJSON(self.columns)
  854. },function (data) {
  855. if (data.status == 0) {
  856. self.collection.id = data.id;
  857. $(document).trigger("info", data.message);
  858. window.location.hash = '#collection=' + data.id;
  859. }
  860. else {
  861. $(document).trigger("error", data.message);
  862. }
  863. }).fail(function (xhr, textStatus, errorThrown) {
  864. $(document).trigger("error", xhr.responseText);
  865. });
  866. };
  867. };