Skip to content

Open Source alternative to Algolia + Pinecone and an Easier-to-Use alternative to ElasticSearch ⚡ 🔍 ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences

Fixed a bug where a document with a duplicate ID was being inserted without an error.

Kishore Nallan85f9887a2fb1
diff --git a/src/collection.cpp b/src/collection.cpp
index 862a2c22..f8439897 100644
--- a/src/collection.cpp
+++ b/src/collection.cpp
@@ -82,6 +82,12 @@ Option<nlohmann::json> Collection::add(const std::string & json_str) {
}
std::string doc_id = document["id"];
+ Option<nlohmann::json> doc_option = get(doc_id);
+
+ // we need to check if document ID already exists before attempting to index
+ if(doc_option.ok()) {
+ return Option<nlohmann::json>(400, std::string("A document with id ") + doc_id + " already exists.");
+ }
const Option<uint32_t> & index_memory_op = index_in_memory(document, seq_id);
diff --git a/test/collection_test.cpp b/test/collection_test.cpp
index b939792e..8f0501ca 100644
--- a/test/collection_test.cpp
+++ b/test/collection_test.cpp
@@ -1479,6 +1479,15 @@ TEST_F(CollectionTest, IndexingWithBadData) {
ASSERT_FALSE(bad_token_ranking_field_op4.ok());
ASSERT_STREQ("Bad JSON.", bad_token_ranking_field_op4.error().c_str());
+ // should return an error when a document with pre-existing id is being added
+ std::string doc = "{\"id\": \"100\", \"name\": \"foo\", \"age\": 29, \"tags\": [], \"average\": 78}";
+ Option<nlohmann::json> add_op = sample_collection->add(doc);
+ ASSERT_TRUE(add_op.ok());
+ add_op = sample_collection->add(doc);
+ ASSERT_FALSE(add_op.ok());
+ ASSERT_EQ(400, add_op.code());
+ ASSERT_STREQ("A document with id 100 already exists.", add_op.error().c_str());
+
collectionManager.drop_collection("sample_collection");
}