search.ko.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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. function magicLayout(vm) {
  17. loadLayout(vm, vm.initial.layout);
  18. $(document).trigger("magicLayout");
  19. }
  20. function loadLayout(viewModel, json_layout) {
  21. var _columns = [];
  22. $(json_layout).each(function (cnt, json_col) {
  23. var _rows = [];
  24. $(json_col.rows).each(function (rcnt, json_row) {
  25. var row = new Row([], viewModel);
  26. $(json_row.widgets).each(function (wcnt, widget) {
  27. row.addWidget(new Widget({
  28. size:widget.size,
  29. id: widget.id,
  30. name: widget.name,
  31. widgetType: widget.widgetType,
  32. properties: widget.properties,
  33. offset: widget.offset,
  34. loading: true,
  35. vm: viewModel
  36. }));
  37. });
  38. _rows.push(row);
  39. });
  40. var column = new Column(json_col.size, _rows);
  41. _columns = _columns.concat(column);
  42. });
  43. viewModel.columns(_columns);
  44. }
  45. // End dashboard lib
  46. var Query = function (vm, query) {
  47. var self = this;
  48. self.qs = ko.mapping.fromJS(query.qs);
  49. self.fqs = ko.mapping.fromJS(query.fqs);
  50. self.start = ko.mapping.fromJS(query.start);
  51. var defaultMultiqGroup = {'id': 'query', 'label': 'query'};
  52. self.multiqs = ko.computed(function () { // List of widgets supporting multiqs
  53. var histogram_id = vm.collection.getHistogramFacet();
  54. return [defaultMultiqGroup].concat(
  55. $.map($.grep(self.fqs(), function(fq, i) {
  56. return (fq.type() == 'field' || fq.type() == 'range') && (histogram_id == null || histogram_id.id() != fq.id());
  57. }), function(fq) { return {'id': fq.id(), 'label': fq.field()} })
  58. );
  59. });
  60. self.selectedMultiq = ko.observable('query');
  61. self.getFacetFilter = function(widget_id) {
  62. var _fq = null;
  63. $.each(self.fqs(), function (index, fq) {
  64. if (fq.id() == widget_id) {
  65. _fq = fq;
  66. return false;
  67. }
  68. });
  69. return _fq;
  70. };
  71. self.getMultiq = ko.computed(function () {
  72. if (self.selectedMultiq()) {
  73. if (self.selectedMultiq() == 'query') {
  74. if (self.qs().length >= 2) {
  75. return 'query';
  76. }
  77. } else {
  78. var facet = self.getFacetFilter(self.selectedMultiq());
  79. if (facet && facet.filter().length > 0) {
  80. return 'facet';
  81. }
  82. }
  83. }
  84. return null;
  85. });
  86. self.addQ = function (data) {
  87. self.qs.push(ko.mapping.fromJS({'q': ''}));
  88. };
  89. self.removeQ = function (query) {
  90. self.qs.remove(query);
  91. };
  92. self.selectedMultiq.subscribe(function () { // To keep below the computed objects!
  93. vm.search();
  94. });
  95. self.toggleFacet = function (data) {
  96. var fq = self.getFacetFilter(data.widget_id);
  97. if (fq == null) {
  98. self.fqs.push(ko.mapping.fromJS({
  99. 'id': data.widget_id,
  100. 'field': data.facet.cat,
  101. 'filter': [{'exclude': data.exclude ? true : false, 'value': data.facet.value}],
  102. 'type': 'field'
  103. }));
  104. } else {
  105. $.each(self.fqs(), function (index, fq) {
  106. if (fq.id() == data.widget_id) {
  107. var f = $.grep(fq.filter(), function(f) { return f.value() == data.facet.value; });
  108. if (f.length > 0) {
  109. fq.filter.remove(f[0]);
  110. if (fq.filter().length == 0) {
  111. self.fqs.remove(fq);
  112. }
  113. } else {
  114. fq.filter.push(ko.mapping.fromJS({'exclude': data.exclude ? true : false, 'value': data.facet.value}));
  115. }
  116. }
  117. });
  118. }
  119. vm.search();
  120. }
  121. self.togglePivotFacet = function (data) {
  122. data.facet.cat = data.facet.fq_fields;
  123. data.facet.value = data.facet.fq_values;
  124. self.toggleFacet(data);
  125. }
  126. function _toggleSingleTermFacet(data, exclude) {
  127. var fq = getFilterByField(data.val.cat);
  128. var id;
  129. if (fq) {
  130. id = fq.id();
  131. } else {
  132. id = UUID();
  133. }
  134. self.toggleFacet({'widget_id': id, 'facet': {'cat': data.val.cat, 'value': data.val.value}, 'exclude': exclude});
  135. vm.search();
  136. }
  137. self.addSingleTermFacet = function(data) {
  138. _toggleSingleTermFacet(data, false);
  139. }
  140. self.removeSingleTermFacet = function(data) {
  141. _toggleSingleTermFacet(data, true);
  142. }
  143. self.selectRangeFacet = function (data) {
  144. if (data.force != undefined) {
  145. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id, 'dontZoomOut': true}));
  146. }
  147. var fq = self.getFacetFilter(data.widget_id);
  148. if (fq == null) {
  149. self.fqs.push(ko.mapping.fromJS({
  150. 'id': data.widget_id,
  151. 'field': data.cat,
  152. 'filter': [{'exclude': data.exclude ? true : false, 'value': data.from}],
  153. 'properties': [{'from': data.from, 'to': data.to}],
  154. 'type': 'range'
  155. }));
  156. } else {
  157. var f = $.grep(fq.filter(), function(f) { return f.value() == data.from; });
  158. if (f.length > 0) { // Unselect
  159. fq.filter.remove(f[0]);
  160. $.each(fq.properties(), function (index, prop) {
  161. if (prop && prop.from() == data.from) {
  162. fq.properties.remove(prop);
  163. }
  164. });
  165. if (fq.filter().length == 0) {
  166. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  167. }
  168. } else {
  169. fq.filter.push(ko.mapping.fromJS({'exclude': data.exclude ? true : false, 'value': data.from}));
  170. fq.properties.push(ko.mapping.fromJS({'from': data.from, 'to': data.to}));
  171. }
  172. }
  173. if (data.no_refresh == undefined) {
  174. vm.search();
  175. }
  176. };
  177. function getFilterByField(field) {
  178. var _fq = null;
  179. $.each(self.fqs(), function (index, fq) {
  180. if (fq.field() == field && fq.id().indexOf('***') == 0) {
  181. _fq= fq;
  182. return false;
  183. }
  184. });
  185. return _fq;
  186. };
  187. self.removeFilter = function (data) {
  188. var found = false;
  189. $.each(self.fqs(), function (index, fq) {
  190. if (fq.id() == data.id()) {
  191. self.fqs.remove(fq);
  192. // Also re-init range select widget
  193. var rangeWidget = vm.collection.getFacetById(fq.id());
  194. if (data.dontZoomOut == undefined && rangeWidget != null && RANGE_SELECTABLE_WIDGETS.indexOf(rangeWidget.widgetType()) != -1 && fq.type() == 'range') {
  195. vm.collection.rangeZoomOut({'id': rangeWidget.id()});
  196. }
  197. found = true;
  198. return false;
  199. }
  200. });
  201. return found;
  202. };
  203. self.paginate = function (direction) {
  204. if (direction == 'next') {
  205. self.start(self.start() + vm.collection.template.rows() * 1.0);
  206. } else {
  207. self.start(self.start() - vm.collection.template.rows() * 1.0);
  208. }
  209. vm.search();
  210. };
  211. };
  212. var FieldAnalysis = function (vm, field_name) {
  213. var self = this;
  214. self.name = ko.observable(field_name);
  215. self.isLoading = ko.observable(true);
  216. self.section = ko.observable('terms');
  217. self.section.subscribe(function () {
  218. self.update();
  219. });
  220. self.terms = ko.mapping.fromJS({'prefix': '', 'data': []});
  221. self.terms.prefix.subscribe(function () {
  222. self.getTerms();
  223. });
  224. self.terms.prefix.extend({rateLimit: {timeout: 2000, method: "notifyWhenChangesStop"}});
  225. self.stats = ko.mapping.fromJS({'facet': '', 'data': []});
  226. var _statsUpdateTimeout = -1;
  227. self.stats.facet.subscribe(function () {
  228. // this is to avoid false positives from typeahead blur
  229. window.clearTimeout(_statsUpdateTimeout);
  230. _statsUpdateTimeout = window.setTimeout(function(){self.getStats()}, 200);
  231. });
  232. self.update = function() {
  233. if (self.section() == 'stats') {
  234. if (self.stats.data().length == 0) {
  235. self.getStats();
  236. }
  237. } else {
  238. if (self.terms.data().length == 0) {
  239. self.getTerms();
  240. }
  241. }
  242. }
  243. self.getTerms = function () {
  244. self.isLoading(true);
  245. self.terms.data.removeAll();
  246. $.post("/search/get_terms", {
  247. collection: ko.mapping.toJSON(vm.collection),
  248. analysis: ko.mapping.toJSON(self)
  249. }, function (data) {
  250. if (data.status == 0) {
  251. if (data.terms != null) {
  252. $.each(data.terms, function (key, val) {
  253. self.terms.data.push({'key': key, 'val': val});
  254. });
  255. }
  256. }
  257. else if (data.status == 1) {
  258. self.terms.data.push({'key': 'Error', 'val': data.message});
  259. }
  260. else {
  261. $(document).trigger("error", data.message);
  262. }
  263. self.isLoading(false);
  264. }).fail(function (xhr, textStatus, errorThrown) {
  265. $(document).trigger("error", xhr.responseText);
  266. });
  267. };
  268. self.getStats = function () {
  269. self.stats.data.removeAll();
  270. self.isLoading(true);
  271. $.post("/search/get_stats", {
  272. collection: ko.mapping.toJSON(vm.collection),
  273. query: ko.mapping.toJSON(vm.query),
  274. analysis: ko.mapping.toJSON(self)
  275. }, function (data) {
  276. if (data.status == 0) {
  277. if (data.stats.stats.stats_fields[self.name()] != null) {
  278. $.each(data.stats.stats.stats_fields[self.name()], function (key, val) {
  279. self.stats.data.push({'key': key, 'val': val});
  280. });
  281. }
  282. }
  283. else if (data.status == 1) {
  284. self.stats.data.push({'key': 'Error', 'val': data.message});
  285. }
  286. else {
  287. $(document).trigger("error", data.message);
  288. }
  289. self.isLoading(false);
  290. }).fail(function (xhr, textStatus, errorThrown) {
  291. $(document).trigger("error", xhr.responseText);
  292. });
  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.extracode($("<span>").html(self.template.extracode()).text()); // Unescape HTML
  307. self.template.extracode.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  308. self.template.template.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  309. self.template.template.subscribe(function () {
  310. vm.search();
  311. });
  312. self.template.isGridLayout.subscribe(function () {
  313. vm.results.removeAll();
  314. vm.search();
  315. });
  316. if (self.template.leafletmap.latitudeField == undefined) {
  317. self.template.leafletmap.latitudeField = ko.observable();
  318. }
  319. if (self.template.leafletmap.longitudeField == undefined) {
  320. self.template.leafletmap.longitudeField = ko.observable();
  321. }
  322. if (self.template.leafletmap.labelField == undefined) {
  323. self.template.leafletmap.labelField = ko.observable();
  324. }
  325. self.template.leafletmapOn = ko.computed(function() {
  326. return self.template.leafletmap.latitudeField() != null && self.template.leafletmap.longitudeField() != null;
  327. });
  328. self.template.leafletmap.latitudeField.subscribe(function (newValue) {
  329. if (self.template.leafletmap.longitudeField() != null && newValue != null) {
  330. vm.search();
  331. }
  332. });
  333. self.template.leafletmap.longitudeField.subscribe(function (newValue) {
  334. if (self.template.leafletmap.latitudeField() != null && newValue != null) {
  335. vm.search();
  336. }
  337. });
  338. self.template.leafletmap.labelField.subscribe(function (newValue) {
  339. if (self.template.leafletmapOn()) {
  340. vm.search();
  341. }
  342. });
  343. self.template.selectedVisualField = ko.observable();
  344. self.template.selectedVisualFunction = ko.observable();
  345. self.template.selectedVisualFunction.subscribe(function (newValue) {
  346. var _vf = $("#visualFunctions");
  347. _vf.siblings(".muted").text(_vf.find(":selected").attr("title"));
  348. });
  349. self.template.selectedSourceField = ko.observable();
  350. self.template.selectedSourceFunction = ko.observable();
  351. self.template.selectedSourceFunction.subscribe(function (newValue) {
  352. var _sf = $("#sourceFunctions");
  353. _sf.siblings(".muted").text(_sf.find(":selected").attr("title"));
  354. });
  355. self.template.addFieldToVisual = function () {
  356. $(document).trigger("addFieldToVisual", self.template.selectedVisualField());
  357. };
  358. self.template.addFunctionToVisual = function () {
  359. $(document).trigger("addFunctionToVisual", self.template.selectedVisualFunction());
  360. };
  361. self.template.addFieldToSource = function () {
  362. $(document).trigger("addFieldToSource", self.template.selectedSourceField());
  363. };
  364. self.template.addFunctionToSource = function () {
  365. $(document).trigger("addFunctionToSource", self.template.selectedSourceFunction());
  366. };
  367. self.facets = ko.mapping.fromJS(collection.facets);
  368. $.each(self.facets(), function (index, facet) {
  369. facet.properties.limit.subscribe(function () {
  370. vm.search();
  371. });
  372. });
  373. self.template.rows.subscribe(function() {
  374. vm.search();
  375. });
  376. self.template.rows.extend({rateLimit: {timeout: 1500, method: "notifyWhenChangesStop"}});
  377. self.fields = ko.mapping.fromJS(collection.fields);
  378. self.availableFacetFields = ko.computed(function() {
  379. var facetFieldNames = $.map(self.facets(), function(facet) {
  380. return facet.field();
  381. });
  382. return $.grep(self.fields(), function(field) {
  383. return facetFieldNames.indexOf(field.name()) == -1;
  384. });
  385. });
  386. self.selectedDocument = ko.observable({});
  387. self.addFacet = function (facet_json) {
  388. self.removeFacet(function(){return facet_json.widget_id});
  389. logGA('add_facet/' + facet_json.widgetType);
  390. $.post("/search/template/new_facet", {
  391. "collection": ko.mapping.toJSON(self),
  392. "id": facet_json.widget_id,
  393. "label": facet_json.name,
  394. "field": facet_json.name,
  395. "widget_type": facet_json.widgetType
  396. }, function (data) {
  397. if (data.status == 0) {
  398. var facet = ko.mapping.fromJS(data.facet);
  399. facet.properties.limit.subscribe(function () {
  400. vm.search();
  401. });
  402. self.facets.push(facet);
  403. vm.search();
  404. } else {
  405. $(document).trigger("error", data.message);
  406. }
  407. }).fail(function (xhr, textStatus, errorThrown) {});
  408. };
  409. self.addPivotFacetValue = function(facet) {
  410. var pivot = null;
  411. if (typeof facet.properties.facets_form.field == 'string') { // Hackish but we load back properties as simple objects
  412. pivot = ko.mapping.fromJS({
  413. 'field': facet.properties.facets_form.field,
  414. 'limit': facet.properties.facets_form.limit,
  415. 'mincount': facet.properties.facets_form.mincount
  416. });
  417. facet.properties.facets_form.field = null;
  418. facet.properties.facets_form.limit = 5;
  419. facet.properties.facets_form.mincount = 1;
  420. } else {
  421. if (typeof facet.properties.facets_form.field != 'undefined') {
  422. pivot = ko.mapping.fromJS({
  423. 'field': facet.properties.facets_form.field(),
  424. 'limit': facet.properties.facets_form.limit(),
  425. 'mincount': facet.properties.facets_form.mincount()
  426. });
  427. facet.properties.facets_form.field(null);
  428. facet.properties.facets_form.limit(5);
  429. facet.properties.facets_form.mincount(1);
  430. }
  431. }
  432. if (pivot != null) {
  433. facet.properties.facets.push(pivot);
  434. vm.search();
  435. }
  436. }
  437. self.removePivotFacetValue = function(facet) {
  438. facet['pivot_facet'].properties.facets.remove(facet['value']);
  439. vm.search();
  440. }
  441. self.removeFacet = function (widget_id) {
  442. $.each(self.facets(), function (index, facet) {
  443. if (facet.id() == widget_id()) {
  444. self.facets.remove(facet);
  445. return false;
  446. }
  447. });
  448. }
  449. self.removeLeaflet = function (widget_json) {
  450. if (widget_json.widgetType() == "leafletmap-widget") {
  451. self.template.leafletmap.latitudeField(null);
  452. self.template.leafletmap.longitudeField(null);
  453. self.template.leafletmap.labelField(null);
  454. }
  455. }
  456. self.getFacetById = function (facet_id) {
  457. var _facet = null;
  458. $.each(self.facets(), function (index, facet) {
  459. if (facet.id() == facet_id) {
  460. _facet = facet;
  461. return false;
  462. }
  463. });
  464. return _facet;
  465. }
  466. self.getFacetByType = function (facetType) {
  467. var _facet = null;
  468. $.each(self.facets(), function (index, facet) {
  469. if (facet.widgetType() == facetType) {
  470. _facet = facet;
  471. return false;
  472. }
  473. });
  474. return _facet;
  475. }
  476. self.getHistogramFacet = function () { // Should do multi histogram
  477. return self.getFacetByType('histogram-widget');
  478. }
  479. self.template.fields = ko.computed(function () {
  480. var _fields = [];
  481. $.each(self.template.fieldsAttributes(), function (index, field) {
  482. var position = self.template.fieldsSelected.indexOf(field.name());
  483. if (position != -1) {
  484. _fields[position] = field;
  485. }
  486. });
  487. return _fields;
  488. });
  489. self.template.fieldsNames = ko.computed(function () {
  490. return $.map(self.template.fieldsAttributes(), function(field) {
  491. return field.name();
  492. });
  493. });
  494. self.getTemplateField = function (name) {
  495. var _field = null;
  496. $.each(self.template.fields(), function (index, field) {
  497. if (field.name() == name) {
  498. _field = field;
  499. return false;
  500. }
  501. });
  502. return _field;
  503. };
  504. self.template.fieldsModalFilter = ko.observable(""); // For UI
  505. self.template.fieldsModalType = ko.observable(""); // For UI
  506. self.template.fieldsAttributesFilter = ko.observable(""); // For UI
  507. self.template.filteredModalFields = ko.observableArray();
  508. self.template.filteredAttributeFieldsAll = ko.observable(true);
  509. self.template.filteredAttributeFields = ko.computed(function() {
  510. var _fields = [];
  511. var _iterable = self.template.fieldsAttributes();
  512. if (! self.template.filteredAttributeFieldsAll()){
  513. _iterable = self.template.fields();
  514. }
  515. $.each(_iterable, function (index, field) {
  516. if (self.template.fieldsAttributesFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsAttributesFilter().toLowerCase()) > -1){
  517. _fields.push(field);
  518. }
  519. });
  520. return _fields;
  521. });
  522. self.template.availableWidgetFields = ko.computed(function() {
  523. if (self.template.fieldsModalType() == 'histogram-widget') {
  524. return vm.availableDateFields();
  525. }
  526. else if (self.template.fieldsModalType() == 'line-widget') {
  527. return vm.availableNumberFields();
  528. }
  529. else if (self.template.fieldsModalType() == 'tree-widget' || self.template.fieldsModalType() == 'heatmap-widget') {
  530. return vm.availablePivotFields();
  531. }
  532. else {
  533. return self.availableFacetFields();
  534. }
  535. });
  536. self.template.availableWidgetFieldsNames = ko.computed(function() {
  537. return $.map(self.template.availableWidgetFields(), function(field) {
  538. return field.name();
  539. });
  540. });
  541. self.template.fieldsModalFilter.subscribe(function(value) {
  542. var _fields = [];
  543. var _availableFields = self.template.availableWidgetFields();
  544. $.each(_availableFields, function (index, field) {
  545. if (self.template.fieldsModalFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  546. _fields.push(field);
  547. }
  548. });
  549. self.template.filteredModalFields(_fields);
  550. });
  551. self.switchCollection = function() { // Long term would be to reload the page
  552. $.post("/search/get_collection", {
  553. name: self.name()
  554. }, function (data) {
  555. if (data.status == 0) {
  556. self.idField(data.collection.collection.idField);
  557. self.template.template(data.collection.collection.template.template);
  558. self.template.fieldsAttributes.removeAll();
  559. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  560. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  561. });
  562. self.fields.removeAll();
  563. $.each(data.collection.collection.fields, function(index, field) {
  564. self.fields.push(ko.mapping.fromJS(field));
  565. });
  566. }
  567. }).fail(function (xhr, textStatus, errorThrown) {});
  568. };
  569. function diff(A, B) {
  570. return A.filter(function (a) {
  571. return B.indexOf(a) == -1;
  572. });
  573. }
  574. function syncArray(currentObservable, newJson, isDynamic) {
  575. // Get names of fields
  576. var _currentFieldsNames = $.map(
  577. $.grep(currentObservable(), function(field) {
  578. return field.isDynamic() == isDynamic;
  579. }), function(field) {
  580. return field.name();
  581. });
  582. var _newFieldsNames = $.map(
  583. $.grep(newJson, function(field) {
  584. return field.isDynamic == isDynamic;
  585. }), function(field) {
  586. return field.name;
  587. });
  588. var _toDelete = diff(_currentFieldsNames, _newFieldsNames);
  589. var _toAdd = diff(_newFieldsNames, _currentFieldsNames);
  590. // Deleted fields
  591. self.template.fieldsSelected.removeAll(_toDelete);
  592. var bulk = $.grep(currentObservable(), function(field) {
  593. return (_toDelete.indexOf(field.name()) != -1)
  594. });
  595. currentObservable.removeAll(bulk);
  596. // New fields
  597. $.each(newJson, function(index, field) {
  598. if (_toAdd.indexOf(field.name) != -1) {
  599. currentObservable.push(ko.mapping.fromJS(field));
  600. }
  601. });
  602. }
  603. self.syncFields = function() {
  604. $.post("/search/get_collection", {
  605. name: self.name()
  606. }, function (data) {
  607. if (data.status == 0) {
  608. self.idField(data.collection.collection.idField);
  609. syncArray(self.template.fieldsAttributes, data.collection.collection.template.fieldsAttributes, false);
  610. syncArray(self.fields, data.collection.collection.fields, false);
  611. }
  612. // After sync the dynamic fields
  613. self.syncDynamicFields()
  614. }).fail(function (xhr, textStatus, errorThrown) {});
  615. };
  616. self.syncDynamicFields = function () {
  617. $.post("/search/index/fields/dynamic", {
  618. name: self.name()
  619. }, function (data) {
  620. if (data.status == 0) {
  621. syncArray(self.template.fieldsAttributes, data.gridlayout_header_fields, true);
  622. syncArray(self.fields, data.fields, true);
  623. }
  624. }).fail(function (xhr, textStatus, errorThrown) {});
  625. };
  626. self.toggleSortColumnGridLayout = function (template_field) {
  627. if (! template_field.sort.direction()) {
  628. template_field.sort.direction('desc');
  629. } else if (template_field.sort.direction() == 'desc') {
  630. template_field.sort.direction('asc');
  631. } else {
  632. template_field.sort.direction(null);
  633. }
  634. $(document).trigger("setResultsHeight");
  635. vm.search();
  636. };
  637. self.toggleSortFacet = function (facet_field, event) {
  638. if (facet_field.properties.sort() == 'desc') {
  639. facet_field.properties.sort('asc');
  640. } else {
  641. facet_field.properties.sort('desc');
  642. }
  643. $(event.target).button('loading');
  644. vm.search();
  645. };
  646. self.toggleRangeFacet = function (facet_field, event) {
  647. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  648. if (facet_field.type() == 'field') {
  649. facet_field.type('range');
  650. } else if (facet_field.type() == 'range') {
  651. facet_field.type('field')
  652. }
  653. $(event.target).button('loading');
  654. vm.search();
  655. };
  656. self.selectTimelineFacet = function (data) {
  657. var facet = self.getFacetById(data.widget_id);
  658. facet.properties.start(data.from);
  659. facet.properties.end(data.to);
  660. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  661. $.ajax({
  662. type: "POST",
  663. url: "/search/get_range_facet",
  664. data: {
  665. collection: ko.mapping.toJSON(self),
  666. facet: ko.mapping.toJSON(facet),
  667. action: 'select'
  668. },
  669. success: function (data) {
  670. if (data.status == 0) {
  671. facet.properties.gap(data.properties.gap);
  672. }
  673. },
  674. async: false
  675. });
  676. vm.search();
  677. }
  678. self.rangeZoomOut = function (facet_json) {
  679. var facet = self.getFacetById(facet_json.id);
  680. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_json.id}));
  681. if (facet.properties.gap() != null) { // Bar, line charts don't have gap
  682. facet.properties.gap(facet.properties.initial_gap());
  683. }
  684. vm.search();
  685. }
  686. self.translateSelectedField = function (index, direction) {
  687. var array = self.template.fieldsSelected();
  688. if (direction == 'left') {
  689. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  690. } else {
  691. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  692. }
  693. };
  694. self.upDownFacetLimit = function (facet_id, direction) {
  695. var facet = self.getFacetById(facet_id);
  696. if (facet.properties.prevLimit == undefined) {
  697. facet.properties.prevLimit = facet.properties.limit();
  698. }
  699. if (direction == 'up') {
  700. facet.properties.limit(facet.properties.limit() + 10);
  701. } else {
  702. facet.properties.limit(facet.properties.limit() - 10);
  703. }
  704. vm.search();
  705. };
  706. };
  707. var NewTemplate = function (vm, initial) {
  708. var self = this;
  709. self.collections = ko.mapping.fromJS(initial.collections);
  710. self.layout = initial.layout;
  711. self.inited = ko.observable(self.collections().length > 0); // No collection if not a new dashboard
  712. self.init = function() {
  713. if (self.inited()) {
  714. // If new dashboard
  715. vm.collection.name.subscribe(function(newValue) {
  716. vm.collection.label(newValue);
  717. vm.collection.switchCollection();
  718. vm.search();
  719. });
  720. } else {
  721. self.syncCollections();
  722. }
  723. if (initial.autoLoad) {
  724. magicLayout(vm);
  725. }
  726. };
  727. self.syncCollections = function () {
  728. $.post("/search/get_collections", {
  729. collection: ko.mapping.toJSON(vm.collection),
  730. }, function (data) {
  731. if (data.status == 0) {
  732. // Sync new and old names
  733. $.each(data.collection, function(index, name) {
  734. if (self.collections.indexOf(name) == -1) {
  735. self.collections.push(name);
  736. }
  737. });
  738. $.each(self.collections(), function(index, collection) {
  739. if (data.collection.indexOf(collection) == -1) {
  740. self.collections.remove(collection);
  741. }
  742. });
  743. }
  744. else {
  745. $(document).trigger("error", data.message);
  746. }
  747. }).fail(function (xhr, textStatus, errorThrown) {
  748. $(document).trigger("error", xhr.responseText);
  749. }).done(function() {
  750. self.inited(true);
  751. });
  752. };
  753. };
  754. var DATE_TYPES = ['date', 'tdate'];
  755. var NUMBER_TYPES = ['int', 'tint', 'long', 'tlong', 'float', 'tfloat'];
  756. var RANGE_SELECTABLE_WIDGETS = ['histogram-widget', 'bar-widget', 'line-widget'];
  757. var SearchViewModel = function (collection_json, query_json, initial_json) {
  758. var self = this;
  759. self.intervalOptions = ko.observableArray(ko.bindingHandlers.daterangepicker.INTERVAL_OPTIONS);
  760. // Models
  761. self.collection = new Collection(self, collection_json.collection);
  762. self.query = new Query(self, query_json);
  763. self.initial = new NewTemplate(self, initial_json);
  764. // UI
  765. self.response = ko.observable({});
  766. self.results = ko.observableArray([]);
  767. self.norm_facets = ko.computed(function () {
  768. return self.response().normalized_facets;
  769. });
  770. self.getFacetFromQuery = function (facet_id) {
  771. var _facet = null;
  772. if (self.norm_facets() !== undefined) {
  773. $.each(self.norm_facets(), function (index, norm_facet) {
  774. if (norm_facet.id == facet_id) {
  775. _facet = norm_facet;
  776. }
  777. });
  778. }
  779. return _facet;
  780. };
  781. self.toggledGridlayoutResultChevron = ko.observable(false);
  782. self.enableGridlayoutResultChevron = function() {
  783. self.toggledGridlayoutResultChevron(true);
  784. };
  785. self.disableGridlayoutResultChevron = function() {
  786. self.toggledGridlayoutResultChevron(false);
  787. };
  788. self.fieldAnalyses = ko.observableArray([]);
  789. self.fieldAnalysesName = ko.observableArray("");
  790. self.fieldsAnalysisAttributesNames = ko.computed(function () {
  791. var _fields = [];
  792. $.each(self.collection.template.fieldsAttributes(), function (index, field) {
  793. if (field.name() != self.fieldAnalysesName()){
  794. _fields.push(field.name())
  795. }
  796. });
  797. return _fields;
  798. });
  799. self.previewColumns = ko.observable("");
  800. self.columns = ko.observable([]);
  801. loadLayout(self, collection_json.layout);
  802. self.isEditing = ko.observable(false);
  803. self.toggleEditing = function () {
  804. self.isEditing(! self.isEditing());
  805. };
  806. self.isRetrievingResults = ko.observable(false);
  807. function bareWidgetBuilder(name, type){
  808. return new Widget({
  809. size: 12,
  810. id: UUID(),
  811. name: name,
  812. widgetType: type
  813. });
  814. }
  815. self.draggableHit = ko.observable(bareWidgetBuilder("Hit Count", "hit-widget"));
  816. self.draggableFacet = ko.observable(bareWidgetBuilder("Facet", "facet-widget"));
  817. self.draggableResultset = ko.observable(bareWidgetBuilder("Grid Results", "resultset-widget"));
  818. self.draggableHtmlResultset = ko.observable(bareWidgetBuilder("HTML Results", "html-resultset-widget"));
  819. self.draggableHistogram = ko.observable(bareWidgetBuilder("Histogram", "histogram-widget"));
  820. self.draggableBar = ko.observable(bareWidgetBuilder("Bar Chart", "bar-widget"));
  821. self.draggableMap = ko.observable(bareWidgetBuilder("Map", "map-widget"));
  822. self.draggableLeafletMap = ko.observable(bareWidgetBuilder("Marker Map", "leafletmap-widget"));
  823. self.draggableLine = ko.observable(bareWidgetBuilder("Line Chart", "line-widget"));
  824. self.draggablePie = ko.observable(bareWidgetBuilder("Pie Chart", "pie-widget"));
  825. self.draggableFilter = ko.observable(bareWidgetBuilder("Filter Bar", "filter-widget"));
  826. self.draggableTree = ko.observable(bareWidgetBuilder("Tree", "tree-widget"));
  827. self.draggableHeatmap = ko.observable(bareWidgetBuilder("Heatmap", "heatmap-widget"));
  828. self.availableDateFields = ko.computed(function() {
  829. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPES.indexOf(field.type()) != -1; });
  830. });
  831. self.availableNumberFields = ko.computed(function() {
  832. return $.grep(self.collection.availableFacetFields(), function(field) { return NUMBER_TYPES.indexOf(field.type()) != -1; });
  833. });
  834. self.availablePivotFields = ko.computed(function() {
  835. return self.collection.fields();
  836. });
  837. function getWidgets(equalsTo) {
  838. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  839. };
  840. self.availableDraggableResultset = ko.computed(function() {
  841. return getWidgets(function(widget) { return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  842. });
  843. self.availableDraggableLeaflet = ko.computed(function() {
  844. return getWidgets(function(widget) { return ['leafletmap-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  845. });
  846. self.availableDraggableFilter = ko.computed(function() {
  847. return getWidgets(function(widget) { return widget.widgetType() == 'filter-widget'; }).length == 0;
  848. });
  849. self.availableDraggableHistogram = ko.computed(function() {
  850. return getWidgets(function(widget) { return widget.widgetType() == 'histogram-widget'; }).length == 0 && self.availableDateFields().length > 0;
  851. });
  852. self.availableDraggableNumbers = ko.computed(function() {
  853. return self.availableNumberFields().length > 0;
  854. });
  855. self.availableDraggableChart = ko.computed(function() {
  856. return self.collection.availableFacetFields().length > 0;
  857. });
  858. self.init = function (callback) {
  859. self.initial.init();
  860. self.collection.syncFields();
  861. self.search(callback);
  862. }
  863. self.searchBtn = function () {
  864. self.query.start(0);
  865. self.search();
  866. };
  867. self.search = function (callback) {
  868. self.isRetrievingResults(true);
  869. $(".jHueNotify").hide();
  870. logGA('search');
  871. // Multi queries
  872. var multiQs = [];
  873. var multiQ = self.query.getMultiq();
  874. if (multiQ != null) {
  875. var facet = {};
  876. var queries = [];
  877. if (multiQ == 'query') {
  878. queries = self.query.qs();
  879. } else {
  880. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  881. queries = $.map(facet.filter(), function(f) { return f.value(); });
  882. }
  883. multiQs = $.map(queries, function(qdata) {
  884. return $.post("/search/get_timeline", {
  885. collection: ko.mapping.toJSON(self.collection),
  886. query: ko.mapping.toJSON(self.query),
  887. facet: ko.mapping.toJSON(facet),
  888. qdata: ko.mapping.toJSON(qdata),
  889. multiQ: multiQ
  890. }, function (data) {return data});
  891. });
  892. }
  893. $.each(self.fieldAnalyses(), function (index, analyse) { // Invalidate stats analysis
  894. analyse.stats.data.removeAll();
  895. });
  896. if (self.getFieldAnalysis()) {
  897. self.getFieldAnalysis().update();
  898. }
  899. $.when.apply($, [
  900. $.post("/search/search", {
  901. collection: ko.mapping.toJSON(self.collection),
  902. query: ko.mapping.toJSON(self.query),
  903. layout: ko.mapping.toJSON(self.columns)
  904. }, function (data) {
  905. if (typeof callback != undefined && callback != null){
  906. callback(data);
  907. }
  908. self.response(data);
  909. self.results.removeAll();
  910. if (data.error) {
  911. $(document).trigger("error", data.error);
  912. }
  913. else {
  914. if (self.collection.template.isGridLayout()) {
  915. // Table view
  916. var _docs = [];
  917. var leafletmap = {};
  918. $.each(data.response.docs, function (index, item) {
  919. var row = [];
  920. var _showDetails = item.showDetails;
  921. var _details = item.details;
  922. delete item["showDetails"];
  923. delete item["details"];
  924. var fields = self.collection.template.fieldsSelected();
  925. // Display selected fields or whole json document
  926. if (fields.length != 0) {
  927. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  928. row.push(item[field]);
  929. });
  930. } else {
  931. row.push(ko.mapping.toJSON(item));
  932. }
  933. if (self.collection.template.leafletmapOn()) {
  934. leafletmap = {
  935. 'latitude': item[self.collection.template.leafletmap.latitudeField()],
  936. 'longitude': item[self.collection.template.leafletmap.longitudeField()],
  937. 'label': self.collection.template.leafletmap.labelField() ? item[self.collection.template.leafletmap.labelField()] : ""
  938. }
  939. }
  940. var doc = {
  941. 'id': item[self.collection.idField()],
  942. 'row': row,
  943. 'showDetails': ko.observable(_showDetails),
  944. 'details': ko.observableArray(_details),
  945. 'leafletmap': leafletmap
  946. };
  947. _docs.push(doc);
  948. });
  949. self.results(_docs);
  950. }
  951. else {
  952. // Template view
  953. var _docs = [];
  954. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  955. $.each(data.response.docs, function (index, item) {
  956. // fix the fields that contain dots in the name
  957. addTemplateFunctions(item);
  958. _docs.push(Mustache.render(_mustacheTmpl, item));
  959. });
  960. self.results(_docs);
  961. }
  962. self.isRetrievingResults(false);
  963. }
  964. })
  965. ].concat(multiQs)
  966. )
  967. .done(function() {
  968. if (arguments[0] instanceof Array) { // If multi queries
  969. var histoFacetId = self.collection.getHistogramFacet().id();
  970. var histoFacet = self.getFacetFromQuery(histoFacetId);
  971. for (var i = 1; i < arguments.length; i++) {
  972. histoFacet.extraSeries.push(arguments[i][0]['series']);
  973. }
  974. self.response.valueHasMutated();
  975. }
  976. })
  977. .fail(function (xhr, textStatus, errorThrown) {
  978. $(document).trigger("error", xhr.responseText);
  979. })
  980. .always(function () {
  981. $('.btn-loading').button('reset');
  982. });
  983. };
  984. self.removeWidget = function (widget_json) {
  985. self.collection.removeFacet(widget_json.id);
  986. self.collection.removeLeaflet(widget_json);
  987. var refresh = self.query.removeFilter(widget_json);
  988. self.removeWidgetById(widget_json.id());
  989. if (refresh) {
  990. self.search();
  991. }
  992. }
  993. self.getWidgetById = function (widget_id) {
  994. var _widget = null;
  995. $.each(self.columns(), function (i, col) {
  996. $.each(col.rows(), function (j, row) {
  997. $.each(row.widgets(), function (z, widget) {
  998. if (widget.id() == widget_id){
  999. _widget = widget;
  1000. return false;
  1001. }
  1002. });
  1003. });
  1004. });
  1005. return _widget;
  1006. }
  1007. self.removeWidgetById = function (widget_id) {
  1008. $.each(self.columns(), function (i, col) {
  1009. $.each(col.rows(), function (j, row) {
  1010. $.each(row.widgets(), function (z, widget) {
  1011. if (widget && widget.id() == widget_id){
  1012. row.widgets.remove(widget);
  1013. row.autosizeWidgets();
  1014. return false;
  1015. }
  1016. });
  1017. });
  1018. });
  1019. }
  1020. self.getDocument = function (doc) {
  1021. $.post("/search/get_document", {
  1022. collection: ko.mapping.toJSON(self.collection),
  1023. id: doc.id
  1024. }, function (data) {
  1025. if (data.status == 0) {
  1026. $.each(data.doc.doc, function(key, val) {
  1027. doc['details'].push(ko.mapping.fromJS({
  1028. key: key,
  1029. value: val
  1030. }));
  1031. });
  1032. }
  1033. else if (data.status == 1) {
  1034. $(document).trigger("info", data.message);
  1035. doc['details'].push(ko.mapping.fromJS({
  1036. key: '',
  1037. value: ''
  1038. }));
  1039. }
  1040. else {
  1041. $(document).trigger("error", data.message);
  1042. }
  1043. }).fail(function (xhr, textStatus, errorThrown) {
  1044. $(document).trigger("error", xhr.responseText);
  1045. });
  1046. };
  1047. self.showFieldAnalysis = function() {
  1048. if (self.fieldAnalysesName()) {
  1049. var analyse = self.getFieldAnalysis();
  1050. if (analyse == null) {
  1051. analyse = new FieldAnalysis(self, self.fieldAnalysesName());
  1052. self.fieldAnalyses.push(analyse);
  1053. }
  1054. analyse.update();
  1055. $(document).trigger("shownAnalysis")
  1056. }
  1057. }
  1058. self.getFieldAnalysis = function() {
  1059. var field_name = self.fieldAnalysesName();
  1060. var _analyse = null;
  1061. $.each(self.fieldAnalyses(), function (index, analyse) {
  1062. if (analyse.name() == field_name) {
  1063. _analyse = analyse;
  1064. return false;
  1065. }
  1066. });
  1067. return _analyse;
  1068. }
  1069. self.save = function () {
  1070. $.post("/search/save", {
  1071. collection: ko.mapping.toJSON(self.collection),
  1072. layout: ko.mapping.toJSON(self.columns)
  1073. }, function (data) {
  1074. if (data.status == 0) {
  1075. self.collection.id = data.id;
  1076. $(document).trigger("info", data.message);
  1077. if (window.location.search.indexOf("collection") == -1) {
  1078. window.location.hash = '#collection=' + data.id;
  1079. }
  1080. }
  1081. else {
  1082. $(document).trigger("error", data.message);
  1083. }
  1084. }).fail(function (xhr, textStatus, errorThrown) {
  1085. $(document).trigger("error", xhr.responseText);
  1086. });
  1087. };
  1088. };
  1089. function logGA(page) {
  1090. if (typeof trackOnGA == 'function') {
  1091. trackOnGA('search/' + page);
  1092. }
  1093. }