检查数百万个搜索查询中是否存在大量单词的有效方法


  1. 我有一个包含5000万个搜索查询的字符串列表。[每个查询1-500+字]。
  2. 我还有一个包含 500 个单词和短语的字符串列表 我需要返回包含任何单词或短语 (2) 的搜索查询 (1) 的索引。

目标是仅保留与特定主题(电影)相关的查询,然后使用 NLP 对这些过滤的查询进行聚类(词干 -> tf_idf -> pca -> kmeans)。

我尝试使用嵌套循环过滤查询,但需要 10 多个小时才能完成。

filtered = []
with open('search_logs.txt', 'r', encoding='utf-8') as f:
for i, line in enumerate(f):
query, timestamp = line.strip().split('t')
for word in key_words:
if word in query:
filtered.append(i)

我研究了使用正则表达式的解决方案(word1|word2|...|wordN),但问题是我无法将查询组合成一个大字符串,因为我需要过滤不相关的查询。

更新:日志和关键字示例

search_logs.txt
'query  timestampn'
'the dark knight    2019-02-17 19:05:12n'
'how to do a barrel roll    2019-02-17 19:05:13n'
'watch movies   2019-02-17 19:05:13n'
'porn   2019-02-17 19:05:13n'
'news   2019-02-17 19:05:14n'
'rami malek 2019-02-17 19:05:14n'
'Traceback (most recent call last): File "t.py" 2019-02-17 19:05:15n'
.......... # millions of other search queries
key_words = [
'movie',
'movies',
'cinema',
'oscar',
'oscars',
'george lucas',
'ben affleck',
'netflix',
.... # hundreds of other words and phrases
]

集合比较 - 杰卡德相似性

Jaccard 相似性是比较一对单词的比较指标:https://www.statology.org/jaccard-similarity/

我会推荐三种方法——

  1. 使用集合比较:将关键字列表保存为集合,然后我们动态将每个查询字符串转换为集合,并将其与关键字集进行比较

例如:

# indexing the keyword list
s = set(keyword)
# pairwise comparison
idx_list = []
for i in range(len(search_arr)):
if set(search_arr[i].split(' ')).intersection(s):
idx_list.append(i)

像这样的东西会让你能够搜索,但在这里,成对比较至少需要 O(N)。

  1. 所以最好的方法是使用反向索引,我们获取搜索查询中的所有唯一单词并构建一个临时索引,然后通过该索引查询关键字,以获取列表索引

例如:

# search query indexing using hashmap
hmap = dict()
for i in range(len(search_list)):
txt = search_list[i].split(' ')
for word in txt:
if word not in hmap:
hmap[word] = set(i)
else:
hmap.add(i)

这基本上将创建您的搜索索引,该索引可用于查询关键字作为反向索引搜索

  1. 如果这效率不高,请尝试使用LSH

https://towardsdatascience.com/understanding-locality-sensitive-hashing-49f6d1f6134

我会推荐FlashText,它被开发为非常有效地处理此类任务。只要您要搜索的关键字是纯字符串(而不是复杂的正则表达式),它就可以工作。

相关内容

最新更新