Migrate Data to CouchDB: Step-by-Step Guide
In this article
- Why CouchDB's Model Changes the Migration Approach
- General Migration Workflow: Extract, Transform, Load
- Tools and Methods for Importing Data
- Handling Data Types and Conflicts
- Migrating from Specific Databases
- Common Pitfalls and How to Avoid Them
- Validating and Testing the Migration
- Frequently Asked Questions
To migrate data to CouchDB from another database, you export your source data to JSON (or CSV), transform it to match CouchDB's document model, and import it via the CouchDB HTTP API or a bulk import tool. The exact steps depend on your source database, but the core process is: extract, transform, load (ETL), with CouchDB's RESTful interface as the final destination.
Why CouchDB's Model Changes the Migration Approach
CouchDB is a document-oriented NoSQL database that stores data as JSON documents. Unlike relational databases with fixed schemas and tables, CouchDB has no predefined schema—each document can have its own structure. This flexibility is powerful, but it means you can't simply copy rows from a SQL table into CouchDB; you need to think in terms of documents and nested data.
For example, a SQL table with columns customer_id, name, and orders (in a separate table) would become a single CouchDB document per customer, with an embedded array of orders. This denormalization is a key difference: CouchDB encourages storing related data together to avoid joins, which are not supported natively.
General Migration Workflow: Extract, Transform, Load
The migration process can be broken into three phases. Here's a typical workflow:
- Export from the source database: Use tools like
pg_dumpfor PostgreSQL,mysqldumpfor MySQL, ormongoexportfor MongoDB to get data in a portable format (SQL, JSON, or CSV). - Transform to JSON: Convert the exported data into JSON documents. For relational data, this means grouping related rows into single documents. For example, a customer and their orders become one document with an
ordersarray. - Import into CouchDB: Use CouchDB's
_bulk_docsendpoint to upload multiple documents in one request, or use a tool likecouchdb-importor a custom script.
Tools and Methods for Importing Data
You have several options for getting JSON into CouchDB:
- HTTP API with
_bulk_docs: POST a JSON array of documents to/db/_bulk_docs. This is the most direct method and works for both small and large datasets. - cURL and command-line tools: Write a script that reads a JSON file and sends it via cURL. For example:
curl -X POST http://localhost:5984/mydb/_bulk_docs -H "Content-Type: application/json" -d @data.json - Third-party ETL tools: Tools like Talend, Apache NiFi, or custom Python scripts using the
requestslibrary can automate the process. - CouchDB's replication feature: If you're migrating from another CouchDB instance or a compatible database (like PouchDB), replication is the easiest method—it syncs data continuously.
Handling Data Types and Conflicts
CouchDB stores data as JSON, so you need to ensure your source data is JSON-compatible. Dates, for instance, should be ISO 8601 strings (e.g., "2025-03-15T10:30:00Z"). Binary data (images, files) should be stored as attachments, not as base64 strings in fields, to keep documents lightweight.
Conflicts arise when two documents have the same _id during import. CouchDB uses optimistic concurrency: each document has a _rev (revision) that changes on every update. If you import a document with an _id that already exists and you don't provide the current _rev, CouchDB will reject it. To avoid this, either let CouchDB generate _ids (by omitting them) or ensure your import script checks for existing documents first.
Migrating from Specific Databases
Each source database has its own quirks:
- From MySQL/PostgreSQL: Use
mysqldumporpg_dumpto export as SQL, then parse the SQL to generate JSON. Alternatively, query the database directly with a script and convert rows to JSON. For large datasets, use a cursor to avoid memory issues. - From MongoDB: Since MongoDB is also document-based, migration is simpler. Use
mongoexportto get JSON, then adjust the structure if needed (e.g., remove MongoDB-specific fields like_idObjectIDs). - From SQL Server: Use the
bcptool to export to CSV, then convert CSV to JSON. Be careful with data types likedatetimeanduniqueidentifier. - From CSV files: Use a tool like
csvtojson(Node.js) or Python'scsvmodule to convert each row to a JSON object.
Common Pitfalls and How to Avoid Them
Here are frequent issues people encounter:
- Large datasets: Uploading millions of documents via
_bulk_docscan time out. Break the import into batches of 1,000–5,000 documents per request. - Data type mismatches: CouchDB doesn't support integers vs. floats distinction—everything is a number. Ensure your JSON uses valid number formats.
- Encoding issues: Non-UTF-8 characters in source data can break JSON. Convert everything to UTF-8 before importing.
- Missing indexes: After migration, create views or Mango indexes to support your queries. Without them, queries will be slow.
Validating and Testing the Migration
After importing, verify the data:
- Check document counts in the source and target (e.g.,
GET /db/_all_docs?limit=0returns total rows). - Spot-check a few documents to ensure fields are correct.
- Run your application's queries against the new database to confirm expected results.
- Test replication if you plan to use it for ongoing sync.
Frequently Asked Questions
Can I migrate from a SQL database without writing code?
Yes, you can use ETL tools like Talend or Apache NiFi that have connectors for both SQL and CouchDB. However, you'll still need to define a mapping from relational tables to JSON documents, which requires some configuration.
How do I handle primary keys from my old database?
You can use the old primary key as the _id field in CouchDB, but ensure it's a valid string. If the old key is an integer, convert it to a string (e.g., "123"). If you don't need the old key, let CouchDB generate UUIDs.
Does CouchDB support importing CSV files directly?
No, CouchDB doesn't have a built-in CSV import. You need to convert CSV to JSON first using a script or a tool like csvtojson.
What is the fastest way to import millions of documents?
Use the _bulk_docs endpoint with batches of 1,000–5,000 documents, and run multiple parallel requests if your server allows. Also, consider disabling the index updates during import by setting "index" to false in the request body, then rebuild indexes afterward.
Can I use CouchDB replication to migrate from another NoSQL database?
Replication only works with databases that implement the CouchDB replication protocol, such as PouchDB or Cloudant. For other NoSQL databases like MongoDB, you'll need a custom ETL process.
What happens to data types like dates and timestamps?
Convert dates to ISO 8601 strings (e.g., "2025-03-15T10:30:00Z") before importing. CouchDB doesn't have a native date type, but you can use strings and sort them lexicographically if they're in ISO format.