1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/ash/components/local_search_service/inverted_index.h"
#include <numeric>
#include <string>
#include <tuple>
#include <vector>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "chromeos/ash/components/local_search_service/search_utils.h"
namespace ash::local_search_service {
namespace {
// (document-score, posting-of-all-matching-terms).
using ScoreWithPosting = std::pair<double, Posting>;
// Calculates TF-IDF scores for a term
std::vector<TfidfResult> CalculateTfidf(const std::u16string& term,
const DocLength& doc_length,
const Dictionary& dictionary) {
std::vector<TfidfResult> results;
// We don't apply weights to idf because the effect is likely small.
const float idf =
1.0 + log((1.0 + doc_length.size()) / (1.0 + dictionary.at(term).size()));
for (const auto& item : dictionary.at(term)) {
// If a term has a very low content weight in a doc, its effective number of
// occurrences in the doc should be lower. Strictly speaking, the effective
// length of the doc should be smaller too. However, for performance
// reasons, we only apply the weight to the term occurrences but not doc
// length.
// TODO(jiameng): this is an expensive operation, we will need to monitor
// its performance and optimize it.
const double effective_term_occ = std::accumulate(
item.second.begin(), item.second.end(), 0.0,
[](double sum, const WeightedPosition& weighted_position) {
return sum + weighted_position.weight;
});
const float tf = effective_term_occ / doc_length.at(item.first);
results.push_back({item.first, item.second, tf * idf});
}
return results;
}
// Builds TF-IDF cache given the data. Since this function is expensive, it
// should run on a non-blocking thread that is different than the main thread.
TfidfCache BuildTfidf(uint32_t num_docs_from_last_update,
const DocLength& doc_length,
const Dictionary& dictionary,
const TermSet& terms_to_be_updated,
const TfidfCache& tfidf_cache) {
// TODO(crbug.com/40152719): consider moving the helper functions inside the
// class so that we can use SequenceChecker.
TfidfCache new_cache(tfidf_cache);
// If number of documents doesn't change from the last time index was built,
// we only need to update terms in |terms_to_be_updated|. Otherwise we need
// to rebuild the index.
if (num_docs_from_last_update == doc_length.size()) {
for (const auto& term : terms_to_be_updated) {
if (dictionary.find(term) != dictionary.end()) {
new_cache[term] = CalculateTfidf(term, doc_length, dictionary);
} else {
new_cache.erase(term);
}
}
} else {
new_cache.clear();
for (const auto& item : dictionary) {
new_cache[item.first] =
CalculateTfidf(item.first, doc_length, dictionary);
}
}
return new_cache;
}
// Removes a document from document state variables given it's ID. Don't do
// anything if the ID doesn't exist. Return true if the document is removed.
bool RemoveDocumentIfExist(const std::string& document_id,
DocLength* doc_length,
Dictionary* dictionary,
TermSet* terms_to_be_updated) {
CHECK(doc_length);
CHECK(dictionary);
CHECK(terms_to_be_updated);
bool document_removed = false;
if (doc_length->find(document_id) == doc_length->end())
return document_removed;
doc_length->erase(document_id);
for (auto it = dictionary->begin(); it != dictionary->end();) {
if (it->second.find(document_id) != it->second.end()) {
terms_to_be_updated->insert(it->first);
it->second.erase(document_id);
document_removed = true;
}
// Removes term from the dictionary if its posting list is empty.
if (it->second.empty()) {
it = dictionary->erase(it);
} else {
it++;
}
}
return document_removed;
}
// Given list of documents to update and document state variables, returns new
// document state variables and number of deleted documents.
std::pair<DocumentStateVariables, uint32_t> UpdateDocumentStateVariables(
DocumentToUpdate&& documents_to_update,
const DocLength& doc_length,
Dictionary&& dictionary,
TermSet&& terms_to_be_updated) {
DocLength new_doc_length(doc_length);
uint32_t num_deleted = 0u;
for (const auto& document : documents_to_update) {
const std::string document_id(document.first);
bool is_deleted = RemoveDocumentIfExist(document_id, &new_doc_length,
&dictionary, &terms_to_be_updated);
// Update the document if necessary.
if (!document.second.empty()) {
// If document content is not empty, it is being updated but not
// deleted.
is_deleted = false;
for (const auto& token : document.second) {
dictionary[token.content][document_id] = token.positions;
new_doc_length[document_id] += token.positions.size();
terms_to_be_updated.insert(token.content);
}
}
num_deleted += (is_deleted) ? 1 : 0;
}
return std::make_pair(
std::make_tuple(std::move(new_doc_length), std::move(dictionary),
std::move(terms_to_be_updated)),
num_deleted);
}
// Given the index variables, clear all the data.
std::pair<DocumentStateVariables, TfidfCache> ClearData(
DocumentToUpdate&& documents_to_update,
const DocLength& doc_length,
Dictionary&& dictionary,
TermSet&& terms_to_be_updated,
TfidfCache&& tfidf_cache) {
DocLength new_doc_length;
documents_to_update.clear();
dictionary.clear();
terms_to_be_updated.clear();
tfidf_cache.clear();
return std::make_pair(
std::make_tuple(std::move(new_doc_length), std::move(dictionary),
std::move(terms_to_be_updated)),
std::move(tfidf_cache));
}
} // namespace
InvertedIndex::InvertedIndex() {
task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(
{base::TaskPriority::BEST_EFFORT, base::MayBlock(),
base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
}
InvertedIndex::~InvertedIndex() = default;
PostingList InvertedIndex::FindTerm(const std::u16string& term) const {
auto it = dictionary_.find(term);
if (it != dictionary_.end()) {
return it->second;
}
return {};
}
std::vector<Result> InvertedIndex::FindMatchingDocumentsApproximately(
const std::unordered_set<std::u16string>& terms,
double prefix_threshold,
double block_threshold) const {
// For each document, its score is the sum of the scores of its terms that
// match one of more query term. Each term's score is the product of its
// TF-IDF score and its match relevance score.
// The map is keyed by the document id.
std::unordered_map<std::string, ScoreWithPosting> matching_docs;
for (const auto& kv : tfidf_cache_) {
const std::u16string& index_term = kv.first;
const std::vector<TfidfResult>& tfidf_results = kv.second;
for (const auto& term : terms) {
const float relevance = RelevanceCoefficient(
term, index_term, prefix_threshold, block_threshold);
if (relevance > 0) {
// If the |index_term| is relevant, all of the enclosing documents will
// have their ranking scores updated.
for (const auto& docid_tfidf : tfidf_results) {
const std::string& docid = std::get<0>(docid_tfidf);
const Posting& posting = std::get<1>(docid_tfidf);
const float tfidf = std::get<2>(docid_tfidf);
auto it = matching_docs.find(docid);
if (it == matching_docs.end()) {
it = matching_docs.emplace(docid, ScoreWithPosting(0.0, {})).first;
}
auto& score_posting = it->second;
// TODO(jiameng): add position penalty.
score_posting.first += tfidf * relevance;
// Also update matching positions.
auto& existing_posting = score_posting.second;
existing_posting.insert(existing_posting.end(), posting.begin(),
posting.end());
}
// Break out from inner loop, i.e. no need to check other query terms.
break;
}
}
}
std::vector<Result> sorted_matching_docs;
for (const auto& kv : matching_docs) {
// We don't need to include weights in the search results.
std::vector<Position> positions;
for (const auto& weighted_position : kv.second.second) {
positions.emplace_back(weighted_position.position);
}
sorted_matching_docs.emplace_back(
Result(kv.first, kv.second.first, positions));
}
std::sort(sorted_matching_docs.begin(), sorted_matching_docs.end(),
CompareResults);
return sorted_matching_docs;
}
void InvertedIndex::AddDocuments(const DocumentToUpdate& documents,
base::OnceCallback<void()> callback) {
if (documents.empty())
return;
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&UpdateDocumentStateVariables, documents,
std::move(doc_length_), std::move(dictionary_),
std::move(terms_to_be_updated_)),
base::BindOnce(&InvertedIndex::OnAddDocumentsComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void InvertedIndex::RemoveDocuments(
const std::vector<std::string>& document_ids,
base::OnceCallback<void(uint32_t)> callback) {
DocumentToUpdate documents;
for (const auto& id : document_ids) {
documents.push_back({id, std::vector<Token>()});
}
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&UpdateDocumentStateVariables, documents,
std::move(doc_length_), std::move(dictionary_),
std::move(terms_to_be_updated_)),
base::BindOnce(&InvertedIndex::OnUpdateDocumentsComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void InvertedIndex::UpdateDocuments(
const DocumentToUpdate& documents,
base::OnceCallback<void(uint32_t)> callback) {
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&UpdateDocumentStateVariables, documents,
std::move(doc_length_), std::move(dictionary_),
std::move(terms_to_be_updated_)),
base::BindOnce(&InvertedIndex::OnUpdateDocumentsComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
std::vector<TfidfResult> InvertedIndex::GetTfidf(
const std::u16string& term) const {
auto it = tfidf_cache_.find(term);
if (it != tfidf_cache_.end()) {
return it->second;
}
return {};
}
void InvertedIndex::BuildInvertedIndex(base::OnceCallback<void()> callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&BuildTfidf, num_docs_from_last_update_, doc_length_,
dictionary_, std::move(terms_to_be_updated_),
tfidf_cache_),
base::BindOnce(&InvertedIndex::OnBuildTfidfComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void InvertedIndex::ClearInvertedIndex(base::OnceCallback<void()> callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&ClearData, std::move(documents_to_update_), doc_length_,
std::move(dictionary_), std::move(terms_to_be_updated_),
std::move(tfidf_cache_)),
base::BindOnce(&InvertedIndex::OnDataCleared,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void InvertedIndex::OnBuildTfidfComplete(base::OnceCallback<void()> callback,
TfidfCache&& new_cache) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
num_docs_from_last_update_ = doc_length_.size();
tfidf_cache_ = std::move(new_cache);
std::move(callback).Run();
}
void InvertedIndex::OnUpdateDocumentsComplete(
base::OnceCallback<void(uint32_t)> callback,
std::pair<DocumentStateVariables, uint32_t>&&
document_state_variables_and_num_deleted) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
doc_length_ =
std::move(std::get<0>(document_state_variables_and_num_deleted.first));
dictionary_ =
std::move(std::get<1>(document_state_variables_and_num_deleted.first));
terms_to_be_updated_ =
std::move(std::get<2>(document_state_variables_and_num_deleted.first));
BuildInvertedIndex(base::BindOnce(
[](base::OnceCallback<void(uint32_t)> callback, uint32_t num_deleted) {
std::move(callback).Run(num_deleted);
},
std::move(callback), document_state_variables_and_num_deleted.second));
}
void InvertedIndex::OnAddDocumentsComplete(
base::OnceCallback<void()> callback,
std::pair<DocumentStateVariables, uint32_t>&&
document_state_variables_and_num_deleted) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(document_state_variables_and_num_deleted.second, 0u);
doc_length_ =
std::move(std::get<0>(document_state_variables_and_num_deleted.first));
dictionary_ =
std::move(std::get<1>(document_state_variables_and_num_deleted.first));
terms_to_be_updated_ =
std::move(std::get<2>(document_state_variables_and_num_deleted.first));
BuildInvertedIndex(std::move(callback));
}
void InvertedIndex::OnDataCleared(
base::OnceCallback<void()> callback,
std::pair<DocumentStateVariables, TfidfCache>&& inverted_index_data) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
doc_length_ = std::move(std::get<0>(inverted_index_data.first));
dictionary_ = std::move(std::get<1>(inverted_index_data.first));
terms_to_be_updated_ = std::move(std::get<2>(inverted_index_data.first));
tfidf_cache_ = std::move(inverted_index_data.second);
num_docs_from_last_update_ = 0;
std::move(callback).Run();
}
} // namespace ash::local_search_service
|