search.ko.js 34 KB

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