search.ko.js 39 KB

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