Skip to content

[ES|QL] Add support for RRF #221349

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 30 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e1d67fb
feat: add rrf node
sddonne May 20, 2025
83b0e3e
feat: add rff ast parser tests
sddonne May 20, 2025
e3b0da1
feat: add rrf to visitor api
sddonne May 20, 2025
084f04b
feat: add tests for rrf pretty printer
sddonne May 21, 2025
d19f0bd
feat: add new rff command and suggestions
sddonne May 22, 2025
06a937e
feat: only display RRF command after a FORK
sddonne May 22, 2025
832a5fa
feat: only display RRF command after FORK
sddonne May 22, 2025
39d8b2d
feat: add tests for rrf autocomplete
sddonne May 22, 2025
36dd3c4
feat: add rrf validations and autocomplete tests
sddonne May 22, 2025
fac9e5c
feat: add validations for rrf command
sddonne May 23, 2025
89b6516
fix: typo
sddonne May 23, 2025
0779540
Merge branch 'main' into esql/rrf/ast-parsing
elasticmachine May 23, 2025
80655ce
add failure test to rrf command parse
sddonne May 23, 2025
36fa32d
Merge branch 'esql/rrf/ast-parsing' of https://github.com/sddonne/kib…
sddonne May 23, 2025
2130458
fix: parameter not needed
sddonne May 23, 2025
37b15c7
unify metada error codes
sddonne May 23, 2025
c19b90a
reuse definition of the metadata fields
sddonne May 26, 2025
297ceca
name it param
sddonne May 26, 2025
1a1f07b
add rrf check directly in the suggest function
sddonne May 26, 2025
c657e50
clean commandsSuggestionsAfter code
sddonne May 26, 2025
4ed4fb3
add test to check there is a pipe between fork and rrf
sddonne May 26, 2025
bb834fd
Merge branch 'main' into esql/rrf/ast-parsing
elasticmachine May 26, 2025
6dc16f1
change rrf metadata error warning
sddonne May 26, 2025
c4a589e
Merge branch 'esql/rrf/ast-parsing' of https://github.com/sddonne/kib…
sddonne May 26, 2025
c49ed97
Merge branch 'main' into esql/rrf/ast-parsing
stratoula May 27, 2025
1d46db4
add rrf test case, when invoked with arguments
sddonne May 27, 2025
17ad55c
fix rrf tests formatting
sddonne May 27, 2025
bdf3b6e
ignore case sensitivity in test regex
sddonne May 28, 2025
509ae43
fix wrong test suite name
sddonne May 28, 2025
0e16d3d
fix: rrf autosuggest test
sddonne May 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { parse } from '../parser';

describe('RRF', () => {
describe('correctly formatted', () => {
it('can parse RRF command without modifiers', () => {
const text = `FROM search-movies METADATA _score, _id, _index
| FORK ( WHERE semantic_title:"Shakespeare" | SORT _score)
( WHERE title:"Shakespeare" | SORT _score)
| RRF
| KEEP title, _score`;

const { root, errors } = parse(text);

expect(errors.length).toBe(0);
expect(root.commands[2]).toMatchObject({
type: 'command',
name: 'rrf',
args: [],
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
type TimeSeriesCommandContext,
type WhereCommandContext,
RerankCommandContext,
RrfCommandContext,
} from '../antlr/esql_parser';
import { default as ESQLParserListener } from '../antlr/esql_parser_listener';
import type { ESQLAst } from '../types';
Expand Down Expand Up @@ -351,6 +352,20 @@ export class ESQLAstBuilderListener implements ESQLParserListener {
this.ast.push(command);
}

/**
* Exit a parse tree produced by `esql_parser.rrfCommand`.
*
* Parse the RRF (Reciprocal Rank Fusion) command:
*
* RRF
*
* @param ctx the parse tree
*/
exitRrfCommand(ctx: RrfCommandContext): void {
const command = createCommand('rrf', ctx);
this.ast.push(command);
}

enterEveryRule(ctx: ParserRuleContext): void {
// method not implemented, added to satisfy interface expectation
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,32 @@ describe('single line query', () => {
);
});
});

describe('RRF', () => {
test('from single line', () => {
const { text } =
reprint(`FROM search-movies METADATA _score, _id, _index | FORK (WHERE semantic_title : "Shakespeare" | SORT _score) (WHERE title : "Shakespeare" | SORT _score) | RRF | KEEP title, _score
`);

expect(text).toBe(
'FROM search-movies METADATA _score, _id, _index | FORK (WHERE semantic_title : "Shakespeare" | SORT _score) (WHERE title : "Shakespeare" | SORT _score) | RRF | KEEP title, _score'
);
});

test('from multiline', () => {
const { text } = reprint(`FROM search-movies METADATA _score, _id, _index
| FORK
(WHERE semantic_title : "Shakespeare" | SORT _score)
(WHERE title : "Shakespeare" | SORT _score)
| RRF
| KEEP title, _score
`);

expect(text).toBe(
'FROM search-movies METADATA _score, _id, _index | FORK (WHERE semantic_title : "Shakespeare" | SORT _score) (WHERE title : "Shakespeare" | SORT _score) | RRF | KEEP title, _score'
);
});
});
});

describe('expressions', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,12 @@ export class ForkCommandVisitorContext<
Data extends SharedData = SharedData
> extends CommandVisitorContext<Methods, Data, ESQLAstCommand> {}

// RRF
export class RrfCommandVisitorContext<
Methods extends VisitorMethods = VisitorMethods,
Data extends SharedData = SharedData
> extends CommandVisitorContext<Methods, Data, ESQLAstCommand> {}

// Expressions -----------------------------------------------------------------

export class ExpressionVisitorContext<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,10 @@ export class GlobalVisitorContext<
if (!this.methods.visitForkCommand) break;
return this.visitForkCommand(parent, commandNode, input as any);
}
case 'rrf': {
if (!this.methods.visitRrfCommand) break;
return this.visitRrfCommand(parent, commandNode, input as any);
}
}
return this.visitCommandGeneric(parent, commandNode, input as any);
}
Expand Down Expand Up @@ -417,6 +421,15 @@ export class GlobalVisitorContext<
return this.visitWithSpecificContext('visitForkCommand', context, input);
}

public visitRrfCommand(
parent: contexts.VisitorContext | null,
node: ESQLAstCommand,
input: types.VisitorInput<Methods, 'visitRrfCommand'>
): types.VisitorOutput<Methods, 'visitRrfCommand'> {
const context = new contexts.RrfCommandVisitorContext(this, node, parent);
return this.visitWithSpecificContext('visitRrfCommand', context, input);
}

// #endregion

// #region Expression visiting -------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ export interface VisitorMethods<
>;
visitForkCommand?: Visitor<contexts.ForkCommandVisitorContext<Visitors, Data>, any, any>;
visitCommandOption?: Visitor<contexts.CommandOptionVisitorContext<Visitors, Data>, any, any>;
visitRrfCommand?: Visitor<contexts.RrfCommandVisitorContext<Visitors, Data>, any, any>;
visitExpression?: Visitor<contexts.ExpressionVisitorContext<Visitors, Data>, any, any>;
visitSourceExpression?: Visitor<
contexts.SourceExpressionVisitorContext<Visitors, Data>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ import { ESQLFieldWithMetadata } from '../validation/types';
import { fieldTypes } from '../definitions/types';
import { ESQLCallbacks } from '../shared/types';

export const metadataFields: ESQLFieldWithMetadata[] = [
{ name: '_id', type: 'keyword' },
{ name: '_index', type: 'keyword' },
{ name: '_score', type: 'double' },
{ name: '_type', type: 'keyword' },
{ name: '_source', type: 'keyword' },
];

export const fields: ESQLFieldWithMetadata[] = [
...fieldTypes.map((type) => ({ name: `${camelCase(type)}Field`, type })),
{ name: 'any#Char$Field', type: 'double' },
Expand Down Expand Up @@ -107,6 +115,9 @@ export function getCallbackMocks(): ESQLCallbacks {
};
return [field];
}
if (/METADATA/.test(query)) {
return [...fields, ...metadataFields];
}
return fields;
}),
getSources: jest.fn(async () =>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { setup } from './helpers';

describe('autocomplete.suggest', () => {
describe('RRF', () => {
it('does not suggest RRF in the general list of commands', async () => {
const { suggest } = await setup();
const suggestedCommands = (await suggest('FROM index | /')).map((s) => s.text);
expect(suggestedCommands).not.toContain('RRF ');
});

it('suggests RRF immediately after a FORK command', async () => {
const { suggest } = await setup();
const suggestedCommands = (await suggest('FROM a | FORK (LIMIT 1) (LIMIT 2) | /')).map(
(s) => s.text
);
expect(suggestedCommands).toContain('RRF ');
});

it('does not suggests RRF if FORK is not immediately before', async () => {
const { suggest } = await setup();
const suggestedCommands = (
await suggest('FROM a | FORK (LIMIT 1) (LIMIT 2) | LIMIT 1 /')
).map((s) => s.text);
expect(suggestedCommands).not.toContain('RRF ');
});

it('suggests pipe after complete command', async () => {
const { assertSuggestions } = await setup();
await assertSuggestions('FROM a | FORK (LIMIT 1) (LIMIT 2) | RRF /', ['| ']);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ export async function suggest(

if (astContext.type === 'newCommand') {
// propose main commands here
// resolve particular commands suggestions after
// filter source commands if already defined
const suggestions = getCommandAutocompleteDefinitions(getAllCommands());
let suggestions = getCommandAutocompleteDefinitions(getAllCommands());
if (!ast.length) {
// Display the recommended queries if there are no commands (empty state)
const recommendedQueriesSuggestions: SuggestionRawDefinition[] = [];
Expand All @@ -144,6 +145,13 @@ export async function suggest(
return [...sourceCommandsSuggestions, ...recommendedQueriesSuggestions];
}

const lastCommand = root.commands[root.commands.length - 1];
const lastCommandDefinition = getCommandDefinition(lastCommand.name);

if (lastCommandDefinition.commandsSuggestionsAfter) {
suggestions = lastCommandDefinition.commandsSuggestionsAfter(suggestions);
}

return suggestions.filter((def) => !isSourceCommand(def));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { CommandDefinition, getCommandDefinition } from '../../../..';
import { getCommandAutocompleteDefinitions } from '../../complete_items';
import { SuggestionRawDefinition } from '../../types';

export function commandsSuggestionsAfter(suggestions: SuggestionRawDefinition[]) {
return [
...suggestions,
...getCommandAutocompleteDefinitions([
{
...(getCommandDefinition('rrf') as CommandDefinition<string>),
hidden: false,
},
]),
];
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@

export { suggest } from './suggest';
export { fieldsSuggestionsAfter } from './fields_suggestions_after';
export { commandsSuggestionsAfter } from './commands_suggestions_after';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { CommandSuggestParams } from '../../../definitions/types';
import type { SuggestionRawDefinition } from '../../types';
import { pipeCompleteItem } from '../../complete_items';

export function suggest(_params: CommandSuggestParams<'rrf'>): SuggestionRawDefinition[] {
return [pipeCompleteItem];
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { suggest as suggestForEval } from '../autocomplete/commands/eval';
import {
suggest as suggestForFork,
fieldsSuggestionsAfter as fieldsSuggestionsAfterFork,
commandsSuggestionsAfter as commandsSuggestionsAfterFork,
} from '../autocomplete/commands/fork';
import { suggest as suggestForFrom } from '../autocomplete/commands/from';
import { suggest as suggestForTimeseries } from '../autocomplete/commands/timeseries';
Expand All @@ -69,6 +70,8 @@ import {
suggest as suggestForRename,
fieldsSuggestionsAfter as fieldsSuggestionsAfterRename,
} from '../autocomplete/commands/rename';
import { suggest as suggestForRrf } from '../autocomplete/commands/rrf';
import { validate as validateRrf } from '../validation/commands/rrf';
import { suggest as suggestForRow } from '../autocomplete/commands/row';
import { suggest as suggestForShow } from '../autocomplete/commands/show';
import { suggest as suggestForSort } from '../autocomplete/commands/sort';
Expand Down Expand Up @@ -705,5 +708,19 @@ export const commandDefinitions: Array<CommandDefinition<any>> = [
},

fieldsSuggestionsAfter: fieldsSuggestionsAfterFork,
commandsSuggestionsAfter: commandsSuggestionsAfterFork,
},
{
hidden: true, // This command should be keep as hidden as it only must be shown after a FORK command
preview: true,
name: 'rrf',
description: i18n.translate('kbn-esql-validation-autocomplete.esql.definitions.rrfDoc', {
defaultMessage:
'Combines multiple result sets with different scoring functions into a single result set.',
}),
declaration: `RRF`, // TODO: update when options are added
examples: ['… FORK (LIMIT 1) (LIMIT 2) | RRF'],
suggest: suggestForRrf,
validate: validateRrf,
},
];
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import type {
import {
ESQLAstItem,
ESQLCommand,
ESQLFunction,
ESQLMessage,
ESQLSource,
ESQLAstCommand,
ESQLAst,
} from '@kbn/esql-ast';
import { ESQLControlVariable } from '@kbn/esql-types';
import { GetColumnsByTypeFn, SuggestionRawDefinition } from '../autocomplete/types';
Expand Down Expand Up @@ -419,7 +420,11 @@ export interface CommandDefinition<CommandName extends string> {
* prevent the default behavior. If you need a full override, we are currently
* doing those directly in the validateCommand function in the validation module.
*/
validate?: (command: ESQLCommand<CommandName>, references: ReferenceMaps) => ESQLMessage[];
validate?: (
command: ESQLCommand<CommandName>,
references: ReferenceMaps,
ast: ESQLAst
) => ESQLMessage[];

/**
* This method is called to load suggestions when the cursor is within this command.
Expand All @@ -434,6 +439,11 @@ export interface CommandDefinition<CommandName extends string> {
previousCommandFields: ESQLFieldWithMetadata[],
userDefinedColumns: ESQLFieldWithMetadata[]
) => ESQLFieldWithMetadata[];

/**
* This method is called to define the commands available after this command is applied.
*/
commandsSuggestionsAfter?: (suggestions: SuggestionRawDefinition[]) => SuggestionRawDefinition[];
}

export interface CommandTypeDefinition {
Expand Down
Loading