I wrote this txtai based python script to query a local Japanese wikipedia vector database. However, I am not getting the correct Japanese wiki articles. Can you fix it for me?
import os
import json
from txtai.embeddings import Embeddings
from datasets import Dataset, concatenate_datasets
import re
import sys
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def escape_sql_string(s) -> str:
# More comprehensive escaping
s = s.replace("\", "\\") # Escape backslashes first
s = s.replace("'", "''") # SQL standard: escape single quotes by doubling
s = s.replace('"', '""') # Escape double quotes by doubling
s = s.replace(";", "") # Remove semicolons
s = s.replace("\n", " ") # Replace newlines with spaces
s = s.replace("\r", " ") # Replace carriage returns
return s
def load_wiki_dataset(path):
"""Load the Wikipedia dataset."""
arrow_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.arrow')]
datasets = [Dataset.from_file(file) for file in arrow_files]
return concatenate_datasets(datasets)
def load_title_to_index(ds, path):
"""Load or create the title to index mapping."""
if os.path.exists(path):
with open(path, 'r') as f:
return json.load(f)
else:
title_to_index = {record['title']: i for i, record in enumerate(ds)}
with open(path, 'w') as f:
json.dump(title_to_index, f)
return title_to_index
prompt = "日中戦争"
sql_prompt = escape_sql_string(prompt)
search_query = f"SELECT id, text, score FROM txtai WHERE similar('{sql_prompt}') and percentile >= 0.1"
wiki_results = embeddings.search(search_query, 20)
if not wiki_results:
print("No wikipedia results found.")
Find top wikipedia articles
for result in wiki_results:
title_id = result['id']
index = title_to_index.get(title_id)
if index is not None:
record = wiki_dataset[index]
print("%s %s" % (record["title"], result['score']))
Assistant
You're trying to build a system that queries a local Japanese Wikipedia vector database using txtai, and you're having trouble getting the correct results.
Let's walk through the issues, improvements, and fixes step-by-step.
🔍 Problem Summary
Your script:
Loads a pre-built txtai embeddings index (paraphrase-multilingual-mpnet-base-v2)
Loads Japanese Wikipedia dataset from .arrow files
Tries to search for "日中戦争" (Sino-Japanese War)
Retrieves results via SQL-like query on txtai
Then tries to map the result IDs back to actual articles in the dataset
✅ What’s working:
Loading of datasets seems okay.
The basic idea of mapping titles to indices is reasonable.
❌ Problems:
Mismatch between txtai index IDs and your dataset
txtai uses its own internal ID space (not tied to your dataset).
If the index was built separately, it may not align with your current dataset's indexing.
Incorrect assumption about id field
In txtai, the id returned by .search() corresponds to the internal ID used when indexing, which may not be the article title or any string identifier unless explicitly set.
No explicit ID during indexing
When building the index, if you didn’t use article titles as IDs, they won’t match later.
title_to_index assumes title → dataset index
But you need a way to map txtai's internal ID → title or content.
✅ Fix Strategy
To fix this, we need to ensure that when building the txtai index, we store the article titles or some unique identifiers so we can retrieve them at query time.
🛠️ Step-by-step Fixes
1. Rebuild the txtai index with explicit IDs (e.g., titles)
If you have control over how the index was built, make sure to do something like this:
# Build the index with explicit IDs (titles)
embeddings = Embeddings(config=embd_config)
# Create list of (id, text, metadata) tuples
index_data = [(record["title"], record["text"], None) for record in wiki_dataset]
embeddings.index(index_data)
embeddings.save("/path/to/saved/index")
This ensures that the id returned by .search() will be the title, making it easy to look up.
If you don't have control over the index building process, and the index doesn't contain titles as IDs, then you'll need to re-map the internal txtai IDs to your dataset.
2. Update Your Search Script
Here's a revised version of your script that assumes the txtai index was built with titles as IDs:
import os
import json
from txtai.embeddings import Embeddings
from datasets import Dataset, concatenate_datasets
def escape_sql_string(s):
s = s.replace("\\", "\\\\").replace("'", "''").replace('"', '""').replace(";", "").replace("\n", " ").replace("\r", " ")
return s
def load_wiki_dataset(path):
arrow_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.arrow')]
datasets = [Dataset.from_file(file) for file in arrow_files]
return concatenate_datasets(datasets)
lang = "ja"
embd_config = {"path": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"}
embeddings = Embeddings(config=embd_config)
# Load the index
embeddings.load(path="/home/user/OfflineWikipediaTextApi/txtai-%s-wikipedia" % lang)
# Load the dataset
wiki_dataset = load_wiki_dataset("/home/user/OfflineWikipediaTextApi/wikipedia-%s/train" % lang)
# Map title -> record in dataset
title_to_record = {record["title"]: record for record in wiki_dataset}
print("Querying...")
prompt = "日中戦争"
sql_prompt = escape_sql_string(prompt)
search_query = f"SELECT id, text, score FROM txtai WHERE similar('{sql_prompt}') AND percentile >= 0.1"
wiki_results = embeddings.search(search_query, 20)
if not wiki_results:
print("No wikipedia results found.")
else:
for result in wiki_results:
title = result['id'] # This should now be the article title
record = title_to_record.get(title)
if record:
print(f"{title} | Score: {result['score']}")
print(record["text"][:500] + "...") # Print excerpt
📌 Key Fixes
Issue
Fix
Mismatched IDs
Use consistent IDs (like article titles) when indexing
No direct mapping
Create a dictionary title -> record instead of title -> index
Poor visibility
Print excerpts of retrieved text to verify relevance
🧪 Optional: Verify Index Was Built Correctly
If you did not build the index yourself, check whether the index actually contains titles as IDs:
# Try retrieving a few items manually
results = embeddings.search("SELECT id FROM txtai LIMIT 5")
print(results)
If the ids are strings like "太平洋戦争" or "日本", then titles were used. If they’re numbers like 0, 1, 2..., then indexes were used — and you’ll need to rebuild the index.
🧰 Bonus: Rebuilding the Index
If you need to rebuild the index, here's a minimal example:
from txtai.embeddings import Embeddings
from datasets import Dataset, concatenate_datasets
# Load dataset
wiki_dataset = load_wiki_dataset("/path/to/wiki/train")
# Configure and create embeddings
embeddings = Embeddings({"path": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"})
# Build index using titles as IDs
index_data = [(record["title"], record["text"], None) for record in wiki_dataset]
embeddings.index(index_data)
# Save index
embeddings.save("/path/to/saved/txtai-index")
✅ Final Notes
Ensure the language model supports Japanese (paraphrase-multilingual-mpnet-base-v2 does).
Make sure both the embedding model and the data are in the same language.
For better performance, consider filtering results by score threshold (e.g., score > 0.3) instead of relying solely on percentile.
💬 Let me know…
If you cannot rebuild the index, or if the index wasn’t built with titles, I can help you write a script to map internal txtai IDs to your dataset based on approximate matching.