search.ko.js 37 KB

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