Repository navigation
add configurable full-text search language #11
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
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,7 +26,7 @@ | |
|
|
||
| from .base import PostgresConnectionManager | ||
| from .filters import apply_filters | ||
| from .utils import psql_quote_literal | ||
| from .utils import psql_quote_literal, psql_regconfig_literal | ||
|
|
||
| logger = logging.getLogger() | ||
|
|
||
|
|
@@ -81,10 +81,15 @@ def __init__( | |
| connection_manager: PostgresConnectionManager, | ||
| dimension: int | float, | ||
| quantization_type: VectorQuantizationType, | ||
| full_text_search_language: str = "english", | ||
| ): | ||
| super().__init__(project_name, connection_manager) | ||
| self.dimension = dimension | ||
| self.quantization_type = quantization_type | ||
| self.full_text_search_language = full_text_search_language | ||
| self.full_text_search_regconfig = psql_regconfig_literal( | ||
| full_text_search_language | ||
| ) | ||
|
|
||
| async def create_tables(self): | ||
| # First check if table already exists and validate dimensions | ||
|
|
@@ -172,12 +177,12 @@ async def create_tables(self): | |
| {binary_col} | ||
| text TEXT, | ||
| metadata JSONB, | ||
| fts tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED | ||
| fts tsvector GENERATED ALWAYS AS (to_tsvector({self.full_text_search_regconfig}, text)) STORED | ||
| ); | ||
| CREATE INDEX IF NOT EXISTS idx_vectors_document_id ON {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} (document_id); | ||
| CREATE INDEX IF NOT EXISTS idx_vectors_owner_id ON {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} (owner_id); | ||
| CREATE INDEX IF NOT EXISTS idx_vectors_collection_ids ON {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} USING GIN (collection_ids); | ||
| CREATE INDEX IF NOT EXISTS idx_vectors_text ON {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} USING GIN (to_tsvector('english', text)); | ||
| CREATE INDEX IF NOT EXISTS idx_vectors_text ON {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} USING GIN (to_tsvector({self.full_text_search_regconfig}, text)); | ||
| """ | ||
|
|
||
| await self.connection_manager.execute_query(query) | ||
|
|
@@ -554,7 +559,9 @@ async def full_text_search( | |
| conditions = [] | ||
| params: list[str | int | bytes] = [query_text] | ||
|
|
||
| conditions.append("fts @@ websearch_to_tsquery('english', $1)") | ||
| conditions.append( | ||
| f"fts @@ websearch_to_tsquery({self.full_text_search_regconfig}, $1)" | ||
| ) | ||
|
|
||
| if search_settings.filters: | ||
| filter_condition, params = apply_filters( | ||
|
|
@@ -573,7 +580,7 @@ async def full_text_search( | |
| collection_ids, | ||
| text, | ||
| metadata, | ||
| ts_rank(fts, websearch_to_tsquery('english', $1), 32) as rank | ||
| ts_rank(fts, websearch_to_tsquery({self.full_text_search_regconfig}, $1), 32) as rank | ||
| FROM {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} | ||
| {where_clause} | ||
| ORDER BY rank DESC | ||
|
|
@@ -1257,8 +1264,8 @@ async def search_documents( | |
| CASE WHEN $1 = '' THEN 0.0 | ||
| ELSE | ||
| ts_rank_cd( | ||
| setweight(to_tsvector('english', {metadata_fields_expr}), 'A'), | ||
| websearch_to_tsquery('english', $1), | ||
| setweight(to_tsvector({self.full_text_search_regconfig}, {metadata_fields_expr}), 'A'), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not just pass the config value verbatim? |
||
| websearch_to_tsquery({self.full_text_search_regconfig}, $1), | ||
| 32 | ||
| ) | ||
| END as metadata_rank | ||
|
|
@@ -1272,14 +1279,14 @@ async def search_documents( | |
| document_id, | ||
| AVG( | ||
| ts_rank_cd( | ||
| setweight(to_tsvector('english', COALESCE(text, '')), 'B'), | ||
| websearch_to_tsquery('english', $1), | ||
| setweight(to_tsvector({self.full_text_search_regconfig}, COALESCE(text, '')), 'B'), | ||
| websearch_to_tsquery({self.full_text_search_regconfig}, $1), | ||
| 32 | ||
| ) | ||
| ) as body_rank | ||
| FROM {self._get_table_name(PostgresChunksHandler.TABLE_NAME)} | ||
| WHERE $1 != '' | ||
| {"AND to_tsvector('english', text) @@ websearch_to_tsquery('english', $1)" if search_over_body else ""} | ||
| {f"AND to_tsvector({self.full_text_search_regconfig}, text) @@ websearch_to_tsquery({self.full_text_search_regconfig}, $1)" if search_over_body else ""} | ||
| GROUP BY document_id | ||
| ), | ||
| -- Combined scores with document metadata | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,10 @@ | ||
| """ | ||
| Database utility functions for PostgreSQL operations. | ||
| """ | ||
| """Database utility functions for PostgreSQL operations.""" | ||
|
|
||
| import re | ||
|
|
||
| _REGCONFIG_NAME_PATTERN = re.compile( | ||
| r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$" | ||
| ) | ||
|
|
||
|
|
||
| def psql_quote_literal(value: str) -> str: | ||
|
|
@@ -10,3 +14,16 @@ def psql_quote_literal(value: str) -> str: | |
| or your database driver's quoting functions. | ||
| """ | ||
| return "'" + value.replace("'", "''") + "'" | ||
|
|
||
|
|
||
| def psql_regconfig_literal(value: str) -> str: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this necessary? Are we guarding against someone putting an invalid config value? |
||
| """Return a validated PostgreSQL regconfig literal. | ||
|
|
||
| Accepts standard text search configuration names like ``english`` or | ||
| schema-qualified names like ``pg_catalog.english``. | ||
| """ | ||
| if not _REGCONFIG_NAME_PATTERN.fullmatch(value): | ||
| raise ValueError( | ||
| f"Invalid PostgreSQL text search configuration: {value}" | ||
| ) | ||
| return f"{psql_quote_literal(value)}::regconfig" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| from types import SimpleNamespace | ||
| from typing import cast | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
|
|
||
| from core.base import DatabaseConfig, SearchSettings, VectorQuantizationType | ||
| from core.providers.database.base import PostgresConnectionManager | ||
| from core.providers.database.chunks import PostgresChunksHandler | ||
| from core.providers.database.documents import PostgresDocumentsHandler | ||
| from core.providers.database.utils import psql_regconfig_literal | ||
|
|
||
|
|
||
| def test_database_config_defaults_full_text_language_to_english(): | ||
| assert DatabaseConfig().full_text_search_language == "english" | ||
|
|
||
|
|
||
| def test_psql_regconfig_literal_rejects_invalid_names(): | ||
| assert psql_regconfig_literal("simple") == "'simple'::regconfig" | ||
|
|
||
| with pytest.raises(ValueError): | ||
| psql_regconfig_literal("english'; DROP TABLE chunks; --") | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_chunks_handler_uses_configured_full_text_language(): | ||
| fetch_query = AsyncMock(side_effect=[[], [], []]) | ||
| execute_query = AsyncMock() | ||
| connection_manager = cast( | ||
| PostgresConnectionManager, | ||
| SimpleNamespace(fetch_query=fetch_query, execute_query=execute_query), | ||
| ) | ||
| handler = PostgresChunksHandler( | ||
| project_name="test_project", | ||
| connection_manager=connection_manager, | ||
| dimension=4, | ||
| quantization_type=VectorQuantizationType.FP32, | ||
| full_text_search_language="simple", | ||
| ) | ||
|
|
||
| await handler.create_tables() | ||
| await handler.full_text_search("foo", SearchSettings()) | ||
|
|
||
| assert execute_query.await_args is not None | ||
| create_query = execute_query.await_args.args[0] | ||
| assert "to_tsvector('simple'::regconfig, text)" in create_query | ||
|
|
||
| assert fetch_query.await_args is not None | ||
| search_query = fetch_query.await_args.args[0] | ||
| assert "websearch_to_tsquery('simple'::regconfig, $1)" in search_query | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_documents_handler_uses_configured_full_text_language(): | ||
| fetch_query = AsyncMock( | ||
| side_effect=[[{"column_name": "total_tokens"}], []] | ||
| ) | ||
| execute_query = AsyncMock() | ||
| connection_manager = cast( | ||
| PostgresConnectionManager, | ||
| SimpleNamespace(fetch_query=fetch_query, execute_query=execute_query), | ||
| ) | ||
| handler = PostgresDocumentsHandler( | ||
| project_name="test_project", | ||
| connection_manager=connection_manager, | ||
| dimension=4, | ||
| full_text_search_language="simple", | ||
| ) | ||
|
|
||
| await handler.create_tables() | ||
| await handler.full_text_document_search("foo", SearchSettings()) | ||
|
|
||
| assert execute_query.await_args is not None | ||
| create_query = execute_query.await_args.args[0] | ||
| assert ( | ||
| "to_tsvector('simple'::regconfig, COALESCE(title, ''))" in create_query | ||
| ) | ||
|
|
||
| assert fetch_query.await_args is not None | ||
| search_query = fetch_query.await_args.args[0] | ||
| assert "websearch_to_tsquery('simple'::regconfig, $1)" in search_query |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changing the
full_text_search_regconfigwill require running a database schema migration. I guess that is missing?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could also raise if someone tries to change the config retroactively.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We are not changing the schema, but only how the index is precomputed. We don't have to do a migration. I also spoke with Alex, and they'll have to re-upload the data to the instances they want to change from English.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We were changing the schema actually 😇