search.ko.js 36 KB

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