search.ko.js 39 KB

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