public function saveWordlist($stems)
{
$terms = [];
$stems->map(function ($column, $key) use(&$terms) {
foreach ($column as $term) {
if (array_key_exists($term, $terms)) {
$terms[$term]['hits']++;
$terms[$term]['docs'] = 1;
} else {
$terms[$term] = ['hits' => 1, 'docs' => 1, 'id' => 0];
}
}
});
$insertStmt = $this->index->prepare("INSERT INTO wordlist (term, num_hits, num_docs) VALUES (:keyword, :hits, :docs)");
$selectStmt = $this->index->prepare("SELECT * FROM wordlist WHERE term like :keyword LIMIT 1");
$updateStmt = $this->index->prepare("UPDATE wordlist SET num_docs = num_docs + :docs, num_hits = num_hits + :hits WHERE term = :keyword");
foreach ($terms as $key => $term) {
try {
$insertStmt->bindParam(":keyword", $key);
$insertStmt->bindParam(":hits", $term['hits']);
$insertStmt->bindParam(":docs", $term['docs']);
$insertStmt->execute();
$terms[$key]['id'] = $this->index->lastInsertId();
if ($this->inMemory) {
$this->inMemoryTerms[$key] = $terms[$key]['id'];
}
} catch (\Exception $e) {
if ($e->getCode() == 23000) {
$updateStmt->bindValue(':docs', $term['docs']);
$updateStmt->bindValue(':hits', $term['hits']);
$updateStmt->bindValue(':keyword', $key);
$updateStmt->execute();
if (!$this->inMemory) {
$selectStmt->bindValue(':keyword', $key);
$selectStmt->execute();
$res = $selectStmt->fetch(PDO::FETCH_ASSOC);
$terms[$key]['id'] = $res['id'];
} else {
$terms[$key]['id'] = $this->inMemoryTerms[$key];
}
} else {
echo $e->getMessage() . "\n";
}
}
}
return $terms;
}