简体   繁体   English

Pouch DB 数据未按排序顺序插入

[英]Pouch DB data is not inserted in sorted order

I am working on small form in electron and pouchdb.我正在 electron 和 pouchdb 中使用小型表格。

When inserting a data into db, until the ninth doc it inserting perfectly, but on 10th doc it is inserting to second position of doc instead on inserting into last将数据插入 db 时,直到第九个文档它插入完美,但在第 10 个文档上它插入到文档的第二个 position 而不是插入到最后一个

before inserting the 10th doc在插入第 10 个文档之前

{
  "total_rows": 9,
  "offset": 0,
    "rows": [
    { "id": "1", "key": "1", "value": {...} },
    { "id": "2", "key": "2", "value": {...} },   
    { "id": "3", "key": "3", "value": {...} },
    { "id": "4", "key": "4", "value": {...} }    
    { "id": "5", "key": "5", "value": {...} },
    { "id": "6", "key": "6", "value": {...} },   
    { "id": "7", "key": "7", "value": {...} },
    { "id": "8", "key": "8", "value": {...} },
    { "id": "9", "key": "9", "value": {...} }
  ]
}

After inserting 10th doc插入第 10 个文档后

{
  "total_rows": 10,
  "offset": 0,
    "rows": [
    { "id": "1", "key": "1", "value": {...} },
    { "id": "10", "key": "10", "value": {...} },
    { "id": "2", "key": "2", "value": {...} },   
    { "id": "3", "key": "3", "value": {...} },
    { "id": "4", "key": "4", "value": {...} }    
    { "id": "5", "key": "5", "value": {...} },
    { "id": "6", "key": "6", "value": {...} },   
    { "id": "7", "key": "7", "value": {...} },
    { "id": "8", "key": "8", "value": {...} },
    { "id": "9", "key": "9", "value": {...} }
  ]
}

here attached the js code这里附上js代码

// form submit
const form = document.getElementById("form1");
form.addEventListener("submit", dbsubmit);

function dbsubmit(e) {
   e.preventDefault();
   //   getting values from form
   var Sno = document.getElementById("number").value
   var date = document.getElementById("date").value;
   var Time = document.getElementById("time").value;
   var Trip = document.querySelector('input[name="Trip"]:checked').value;
   var TripType = document.querySelector('input[name="Type"]:checked').value;
 
 // assigning form values to db table names
  var doc = {
    _id: Sno,
    Date: date,
    time: Time,
    trip: Trip,
    triptype: TripType,
  };

   // inserting to db
  db.put(doc, function(err, response) {
    if (err) {
      return console.log(err);
    } else {
      console.log("Document created Successfully", response);
    }
  });
}

Inserting until ninth 9th doc it's perfectly inserting but when inserting the 10th doc it is inserting in second position.插入到第 9 个 9th doc 时它完美地插入但是当插入第 10 个 doc 时它插入第二个 position。

The doc should be sorted by id and want to use it to view in another page.该文档应按 id 排序,并希望使用它在另一个页面中查看。

I debugged but cannot find a solution, can anyone help me with the solution?我调试了但找不到解决方案,谁能帮我解决这个问题?

Thank you谢谢

You have an errant notion regarding document insertion, whether as if the order of insertion with respect to time matters which is to be expected from say an RDBMS like MS/SQL, or a belief that a string representation of a numeric value should be sorted according to the implied numerical value (which would be wild guessing by the db).您对文档插入有一个错误的概念,无论是关于时间的插入顺序很重要,这是从像 MS/SQL 这样的 RDBMS 中可以预期的,或者认为应该根据数字值的字符串表示进行排序到隐含的数值(这将是数据库的疯狂猜测)。

As explicitly stated here , here and here , and as specified by the CouchDB documentation 3.2.2.5.正如此处此处此处以及 CouchDB 文档3.2.2.5 所指定的那样。 Collation Specification 归类规范

Comparison of strings is done using ICU which implements the Unicode Collation Algorithm, giving a dictionary sorting of keys.字符串的比较是使用 ICU 完成的,它实现了 Unicode 归类算法,给出了键的字典排序。 This can give surprising results if you were expecting ASCII ordering.如果您期望 ASCII 排序,这会产生令人惊讶的结果。

Documents are not returned by order of insertion rather they are returned according to the collation rules applied to the document ids, and document ids are strings .文档不是按插入顺序返回的,而是根据应用于文档 id 的排序规则返回的,文档 id 是strings

For example you expect this ordering:例如,您期望这样的顺序:

row #排 # id ID
0 0 1 1个
1 1个 2 2个
2 2个 3 3个
3 3个 4 4个
4 4个 5 5个
5 5个 6 6个
6 6个 7 7
7 7 8 8个
8 8个 9 9
9 9 10 10

BUT that is not according to the collation rules, which yields但是这不符合整理规则,这会产生

row #排 # id ID
0 0 1 1个
1 1个 10 10
2 2个 2 2个
3 3个 3 3个
4 4个 4 4个
5 5个 5 5个
6 6个 6 6个
7 7 7 7
8 8个 8 8个
9 9 9 9

Again, it cannot be emphasized enough that the order of insertion, much less an implied numeric value, does not affect the order of results.再次强调,插入顺序(更不用说隐含的数值)不会影响结果的顺序,这一点再怎么强调也不为过。 From an RDBMS perspective it is helpful to approach _all_docs results as being ordered by an index on _id which is sorted according to collation rules (again, for strings since all _id s are of type string).从 RDBMS 的角度来看,将 _all_docs 结果视为由_id上的索引排序是有帮助的,该索引根据排序规则排序(同样,对于字符串,因为所有_id都是字符串类型)。

The snippet below demonstrates this by creating 100 documents with ids ranging from 1 to 100.下面的代码片段通过创建 100 个 ID 范围从 1 到 100 的文档来演示这一点。

 // generate canned test documents with doc _id's in the range 1 to 100. function getDocsToInstall() { let docs = []; for (let i = 1; i < 101; i++) { // _id must be a string type because that's the way it is, period. docs.push({ _id: i.toString() }); } return docs; } let db; // init db instance async function initDb() { db = new PouchDB('test', { adapter: 'memory' }); await db.bulkDocs(getDocsToInstall()); } initDb().then(async() => { let options = { limit: 25, include_docs: false, reduce: false }; const result = await db.allDocs(options); showResult(result); }); function gel(id) { return document.getElementById(id); } function cel(name) { return document.createElement(name); } function addColumn(tr, value) { const td = cel('td'); td.innerText = value; tr.append(td); } function addRow(row, index) { const tr = cel('tr'); [index, row.id].forEach(value => addColumn(tr, value)); gel('table').append(tr); } function showResult(result) { const table = gel('table'); result.rows.forEach((row, index) => { addRow(row, index); }); }
 th, td { padding: .5em; text-align: left; min-width: 4em; } table { border-collapse: collapse; }
 <script src="https://cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script> <script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script> <table id="table" border="1"> <tr> <th>row #</th> <th>id</th> </tr> </table>

The must-get takeaway from the snippet is that the first 3 documents returned are从代码片段中必须得到的结论是返回的前 3 个文档是

row #排 # id ID
0 0 1 1个
1 1个 10 10
2 2个 100 100

As janl pointed out here if you need to access documents in terms of numerical ordering, then creating a view is a good option, which the following snippet demonstrates.正如janl 在这里指出的那样,如果您需要按照数字顺序访问文档,那么创建视图是一个不错的选择,以下代码片段对此进行了演示。

The snippet shows results from _all_docs and the my_index view side by side.该片段并排显示了 _all_docs 和 my_index 视图的结果。

 // generate canned test documents with doc _id's in the range 1 to 100. function getDocsToInstall() { let docs = []; for (let i = 1; i < 101; i++) { // _id must be a string type because that's the way it is, period. docs.push({ _id: i.toString() }); } // add a design doc/view for numerically ordered documents docs.push({ _id: '_design/my_ddoc', views: { my_index: { map: function(doc) { emit(Number(doc._id)); }.toString() } } }) return docs; } let db; // init db instance async function initDb() { db = new PouchDB('test', { adapter: 'memory' }); await db.bulkDocs(getDocsToInstall()); } initDb().then(async() => { let options = { limit: 25, include_docs: false, reduce: false }; const allDocs = await db.allDocs(options); const view = await db.query('my_ddoc/my_index'); showResult(allDocs, view); }); function gel(id) { return document.getElementById(id); } function cel(name) { return document.createElement(name); } function addColumn(tr, value) { const td = cel('td'); td.innerText = value; tr.append(td); } function addRow(index, allDocs, view) { const tr = cel('tr'); [index, allDocs.rows[index].key, view.rows[index].key].forEach(value => addColumn(tr, value)); gel('table').append(tr); } // show allDocs and view results side by side function showResult(allDocs, view) { const table = gel('table'); for (let i = 0; i < allDocs.rows.length; i++) { addRow(i, allDocs, view); }; }
 th, td { padding: .5em; text-align: left; min-width: 4em; } table { border-collapse: collapse; }
 <script src="https://cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script> <script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script> <table id="table" border="1"> <tr> <th>row #</th> <th>_all_docs key</th> <th>my_index key</th> </tr> </table>

Note that for _all_docs, key and id are the document _id .请注意,对于 _all_docs, keyid是文档_id It's important to understand that _all_docs is in fact a built-in view which explains why key and id are present in _all_docs results.重要的是要了解 _all_docs 实际上是一个内置视图,它解释了为什么keyid出现在 _all_docs 结果中。

If in fact you want documents ordered with respect to time , then add a creation timestamp to documents and build a view based on that timestamp, eg the map function might look like this if creationTime is an integer representing a point in time (milliseconds) in the Unix epoch.如果实际上您希望文档根据时间排序,则向文档添加创建时间戳并基于该时间戳构建视图,例如,如果creationTime是表示时间点(毫秒)的 integer,则 map function 可能看起来像这样Unix 纪元。

function(doc) {
   emit(doc.creationTime);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM