search.ko.js 34 KB

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