search.ko.js 37 KB

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