language_provider.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { AbstractLabelOperator, AbstractLabelMatcher, LanguageProvider, AbstractQuery } from '@grafana/data';
  2. import { ElasticDatasource } from './datasource';
  3. import { ElasticsearchQuery } from './types';
  4. export default class ElasticsearchLanguageProvider extends LanguageProvider {
  5. declare request: (url: string, params?: any) => Promise<any>;
  6. declare start: () => Promise<any[]>;
  7. datasource: ElasticDatasource;
  8. constructor(datasource: ElasticDatasource, initialValues?: any) {
  9. super();
  10. this.datasource = datasource;
  11. Object.assign(this, initialValues);
  12. }
  13. /**
  14. * Queries are transformed to an ES Logs query since it's the behaviour most users expect.
  15. **/
  16. importFromAbstractQuery(abstractQuery: AbstractQuery): ElasticsearchQuery {
  17. return {
  18. metrics: [
  19. {
  20. id: '1',
  21. type: 'logs',
  22. },
  23. ],
  24. query: this.getElasticsearchQuery(abstractQuery.labelMatchers),
  25. refId: abstractQuery.refId,
  26. };
  27. }
  28. getElasticsearchQuery(labels: AbstractLabelMatcher[]): string {
  29. return labels
  30. .map((label) => {
  31. switch (label.operator) {
  32. case AbstractLabelOperator.Equal: {
  33. return label.name + ':"' + label.value + '"';
  34. }
  35. case AbstractLabelOperator.NotEqual: {
  36. return 'NOT ' + label.name + ':"' + label.value + '"';
  37. }
  38. case AbstractLabelOperator.EqualRegEx: {
  39. return label.name + ':/' + label.value + '/';
  40. }
  41. case AbstractLabelOperator.NotEqualRegEx: {
  42. return 'NOT ' + label.name + ':/' + label.value + '/';
  43. }
  44. }
  45. })
  46. .join(' AND ');
  47. }
  48. }