Support segmented Chinese queries, phrase matching and type filters
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
use std::collections::BTreeSet;
|
||||
use jieba_rs::Jieba;
|
||||
use std::{collections::BTreeSet, sync::OnceLock};
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
pub(crate) fn normalize(text: &str) -> String {
|
||||
@@ -54,5 +55,23 @@ pub(crate) fn index_tokens(text: &str) -> Vec<String> {
|
||||
}
|
||||
|
||||
pub(crate) fn query_terms(text: &str) -> BTreeSet<String> {
|
||||
tokens(text, false).into_iter().collect()
|
||||
static LEXICON: OnceLock<Jieba> = OnceLock::new();
|
||||
let mut terms = BTreeSet::new();
|
||||
let mut rest = text;
|
||||
while let Some(first) = rest.chars().next() {
|
||||
let is_han = han(first);
|
||||
let end = rest.find(|c: char| han(c) != is_han).unwrap_or(rest.len());
|
||||
let (run, tail) = rest.split_at(end);
|
||||
if is_han {
|
||||
// Segment only the query. The existing character/bigram postings can
|
||||
// match each dictionary word even in names absent from the dictionary.
|
||||
for word in LEXICON.get_or_init(Jieba::new).cut(run, false) {
|
||||
terms.extend(tokens(word, false));
|
||||
}
|
||||
} else {
|
||||
terms.extend(tokens(run, false));
|
||||
}
|
||||
rest = tail;
|
||||
}
|
||||
terms
|
||||
}
|
||||
|
||||
@@ -38,6 +38,13 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
hits: Vec::new(),
|
||||
};
|
||||
let text = analysis::normalize(query.text);
|
||||
// Only closed quote pairs are operators; an unmatched trailing quote is punctuation.
|
||||
let parts: Vec<_> = text.split('"').skip(1).collect();
|
||||
let phrases: Vec<_> = parts
|
||||
.chunks_exact(2)
|
||||
.map(|pair| pair[0].trim())
|
||||
.filter(|phrase| !phrase.is_empty())
|
||||
.collect();
|
||||
let mut lists = Vec::new();
|
||||
for term in analysis::query_terms(&text) {
|
||||
let Some(postings) = reader.postings(&term)? else {
|
||||
@@ -66,6 +73,12 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !phrases
|
||||
.iter()
|
||||
.all(|phrase| entry.title.contains(phrase) || entry.body.contains(phrase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if query.limit == 0 || query.offset >= first.len() {
|
||||
continue;
|
||||
|
||||
Reference in New Issue
Block a user