支持限定公开来源与排除文字的 Telegram 搜索 #2

Merged
Zayden-Jung merged 1 commits from codex/query-refinements into main 2026-12-02 19:24:56 +00:00
7 changed files with 113 additions and 8 deletions
Showing only changes of commit 20d3d3fc62 - Show all commits
+1 -1
View File
@@ -24,7 +24,7 @@ cargo run -p telefind-app -- bot events.jsonl
The input file is optional. The process identifies its username via `getMe`, then long-polls for incoming messages and sends search results with URL buttons. Type keywords in private chat or use `/search@YourBot keywords` in a group. In a public channel where the bot receives posts, incoming posts and edits update the in-memory index. For channels without a public username, protected posts and unsupported content, the bot skips indexing the message. Telegram does not send ordinary post-deletion notifications via this update stream. An upstream source can supply deletion events. If a reply reached Telegram but its HTTP acknowledgement was lost, retrying an update can send the reply twice.
Use a leading `type:channel`, `type:group`, `type:bot`, `type:post`, `type:photo`, `type:video`, `type:audio` or `type:file` to filter. Double quotes require a contiguous phrase in one field. Use `/page 2 type:video 摄影` to repeat a query on another page.
Use a leading `type:channel`, `type:group`, `type:bot`, `type:post`, `type:photo`, `type:video`, `type:audio` or `type:file` to filter. After the optional type filter, add `from:@username` to restrict the source, or `exclude:广告` to omit titles and bodies containing that normalized text fragment. Multiple exclusions are allowed. Follow the filters with search terms, for example `/search type:video from:@example_feed exclude:广告 相机`. Double quotes require a contiguous phrase in one field. Use `/page 2 type:video 摄影` to repeat a query on another page.
## Document input and storage
+1 -1
View File
@@ -101,7 +101,7 @@ pub fn render(reply: Reply) -> Option<Value> {
match reply {
Reply::Ignored => None,
Reply::Help => Some(
json!({"text":"发送关键词或 /search 关键词。可用 type:channel、group、bot、post、video、photo、audio、file 筛选;用 /page 页码 关键词 翻页。"}),
json!({"text":"发送关键词或 /search 关键词。可用 type:channel、group、bot、post、video、photo、audio、file 筛选;可在关键词前加 from:@频道名 限定来源,或 exclude:广告 排除含该文字的结果。用 /page 页码 关键词 翻页。"}),
),
Reply::Results { total, links } if links.is_empty() => Some(
json!({"text":if total == 0 {"没有找到匹配结果。".into()} else {format!("本页没有结果,共 {total} 条。")}}),
+30
View File
@@ -102,3 +102,33 @@ fn type_filter_is_available_in_search_and_page_commands() {
Reply::Help
);
}
#[test]
fn scoped_media_search_keeps_quoted_phrase_and_original_link() {
let mut index = MemoryIndex::default();
for (message, body) in [
(1, "Rust search"),
(2, "Rust search SALE"),
(3, "search Rust"),
] {
index
.upsert(Document {
id: DocumentId::Post { chat: 3, message },
username: PublicName::new("my_feed").unwrap(),
title: String::new(),
body: body.into(),
media: Some(telefind_core::Media::Video),
})
.unwrap();
}
let Reply::Results { total, links } = handle(
&index,
"me",
r#"/page@me 1 type:video from:@My_Feed exclude:sale "rust search""#,
)
.unwrap() else {
panic!("expected a search result")
};
assert_eq!(total, 1);
assert_eq!(links[0].url, "https://t.me/my_feed/1");
}
+1
View File
@@ -1,6 +1,7 @@
pub(crate) mod analysis;
pub(crate) mod rank;
pub(crate) mod retrieve;
mod scope;
use crate::{Document, Kind, Media};
+10 -6
View File
@@ -1,4 +1,4 @@
use super::{analysis, rank};
use super::{analysis, rank, scope::Scope};
use crate::{index::IndexReader, DocumentId, Kind, Query, SearchPage};
use std::{
cmp::{Ordering, Reverse},
@@ -37,7 +37,10 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
total: 0,
hits: Vec::new(),
};
let text = analysis::normalize(query.text);
let normalized = analysis::normalize(query.text);
let Some((scope, text)) = Scope::parse(&normalized) else {
return Ok(empty());
};
// Only closed quote pairs are operators; an unmatched trailing quote is punctuation.
let parts: Vec<_> = text.split('"').skip(1).collect();
let phrases: Vec<_> = parts
@@ -46,7 +49,7 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
.filter(|phrase| !phrase.is_empty())
.collect();
let mut lists = Vec::new();
for term in analysis::query_terms(&text) {
for term in analysis::query_terms(text) {
let Some(postings) = reader.postings(&term)? else {
return Ok(empty());
};
@@ -66,7 +69,8 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
continue;
}
let entry = reader.document(*id)?;
if query.kind.is_some_and(|kind| kind != entry.document.kind())
if !scope.accepts(&entry)
|| query.kind.is_some_and(|kind| kind != entry.document.kind())
|| query
.media
.is_some_and(|media| Some(media) != entry.document.media)
@@ -87,9 +91,9 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
.iter()
.map(|list| rank::term_score(list[id], entry.lengths, avg, n, list.len()))
.sum();
if entry.title.contains(&text) {
if entry.title.contains(text) {
score += 2.0;
} else if entry.body.contains(&text) {
} else if entry.body.contains(text) {
score += 0.5;
}
let exact = entry.document.kind() != Kind::Post
+42
View File
@@ -0,0 +1,42 @@
//! Leading source and exclusion filters in normalized search text.
use crate::{index::IndexedDocument, PublicName};
#[derive(Default)]
pub(super) struct Scope<'a> {
source: Option<PublicName>,
excluded: Vec<&'a str>,
}
impl<'a> Scope<'a> {
pub fn parse(mut text: &'a str) -> Option<(Self, &'a str)> {
let mut scope = Self::default();
loop {
let (token, rest) = text.split_once(' ').unwrap_or((text, ""));
if let Some(source) = token.strip_prefix("from:") {
let name = PublicName::new(source)?;
if scope.source.as_ref().is_some_and(|s| s != &name) {
return None;
}
scope.source = Some(name);
} else if let Some(fragment) = token.strip_prefix("exclude:") {
if fragment.is_empty() {
return None;
}
scope.excluded.push(fragment);
} else {
return Some((scope, text));
}
text = rest;
}
}
pub fn accepts(&self, entry: &IndexedDocument) -> bool {
self.source
.as_ref()
.is_none_or(|s| s == &entry.document.username)
&& !self
.excluded
.iter()
.any(|f| entry.title.contains(f) || entry.body.contains(f))
}
}
+28
View File
@@ -183,3 +183,31 @@ fn measure_ranked_queries_over_25000_posts() {
);
}
}
#[test]
fn source_and_exclusions_apply_before_total_and_offset() {
let mut index = MemoryIndex::default();
for (chat, message, title, body) in [
(1, 1, "相机 广告", ""),
(1, 2, "相机", "转发"),
(1, 3, "相机", ""),
(1, 4, "相机", ""),
(2, 1, "相机", ""),
] {
index.upsert(post(chat, message, title, body)).unwrap();
}
let mut query = Query::new("exclude:广告 from:@CHAT1 exclude:转发 相机");
query.offset = 1;
query.limit = 1;
let page = index.search(&query).unwrap();
assert_eq!(page.total, 2);
assert_eq!(page.hits[0].url(), "https://t.me/chat1/4");
for invalid in [
"from:@x/y 相机",
"from:chat1 from:chat2 相机",
"exclude: 相机",
"from:chat1",
] {
assert_eq!(index.search(&Query::new(invalid)).unwrap().total, 0);
}
}