An adaptive hash index storage and fast retrieval system for a small program cash register system

CN122527083APending Publication Date: 2026-08-07张亮
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610877522.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-06-17
Publication Date
2026-08-07

AI Technical Summary

Technical Problem

[0009](2)进程随时可能被系统灭活

Benefits of technology

[0028](5)异常场景下的数据可靠性验证。 在模拟测试中,执行以下流程100次:应用完成收银结算(内存中暂存最新商品数组和交易流水,尚未触发如权利要求3所述的100毫秒定时器落盘)→模拟系统灭活(强制终止应用进程)→重新启动应用→读取持久化JSON文件→验证商品库存数据与交易流水记录的完整性。100次测试中数据零丢失、零损坏,证明步骤S2中检测到应用进入后台状态时的强制刷盘机制切实解决了"进程临被杀时数据丢失"的技术问题。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122527083A_ABST
    Figure CN122527083A_ABST
Patent Text Reader

Abstract

The application discloses a kind of applet cash register system's adaptive hash index storage and fast retrieval method, it is applied to the running environment of no database engine, only synchronous file API, process can be inactivated at any time.Core is S1 constructs barcode→array subscript hash mapping table, S2 delay merges and writes and background forced flush, S3 based on hash mapping table's commodity query and barcode consistency check, S4 four steps cooperation after each landing table full reconstruction mapping table: S2 delay window can lead to subscript drift, S3 is detected by barcode consistency check structural drift (different from the data content expiration of general cache check detection), and inconsistent triggers full reconstruction after requery;S4 landing table full reconstruction mapping table eliminates cumulative effect.Auxiliary mechanism includes recursive emptying compact writing, according to two level lazy loading of monthly fragmentation, expired data automatic cleaning.The above mechanism is also extended to key-value mapping table system.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of local data storage and retrieval technology for mobile applications, specifically to a local data storage and efficient retrieval method and system that works in a restricted operating environment for mini-programs (without a structured database engine, using a synchronous file system interface as the data persistence method, and where the application process may be terminated by the system at any time). This method and system work together with the merge write and forced disk flushing mechanism in step S2 and the product query and consistency verification mechanism in step S3, supplemented by the index synchronous reconstruction in step S4. Background Technology

[0002] Mini-programs face storage constraints as retail POS platforms. With an ecosystem covering over 1 billion users, the mini-program is an ideal platform for retail POS systems for small and micro-sized merchants. However, current data management for retail POS systems in small and micro-sized merchants primarily relies on the following solutions, each with its own specific bottlenecks: Option A: Dedicated POS hardware. This involves using dedicated POS hardware with a built-in SQLite database and embedded indexing engine (such as POS machines from brands like Sunmi and Keruyun). The purchase cost per device is approximately ¥3,000-8,000. Field surveys revealed that small and micro-sized businesses (convenience stores, mini-supermarkets, stationery stores, etc., with operating data referenced from the "2025 China Convenience Store Development Report")... [1] Typical daily transactions are 50-200, and the number of product SKUs is 2,000 for chain convenience stores and 4,000 for takeout warehouses. Most businesses are taking a wait-and-see approach to this type of specialized equipment. In addition to the high cost of hardware procurement, the difficulty of operation training and the reliance on equipment service providers for daily maintenance make it difficult for small and micro merchants with a single checkout point to recover their investment within a reasonable period.

[0003] Option B: Cloud Database Service. This option uses a regular mobile phone / tablet in conjunction with a cloud database (MySQL / PostgreSQL / cloud database) such as a WeChat Mini Program cloud development platform for data read and write. Cloud service costs must be covered by purchasing cloud services or by purchasing software licenses. Furthermore, this option relies on a continuous network connection; in environments with unstable or no network access (such as underground shopping malls or remote rural shops), all functions become unavailable, and the checkout process is interrupted. Many existing checkout and order processing applications based on the WeChat Mini Program platform (such as Yinbao Checkout) use this type of cloud database solution, requiring merchants to continuously pay cloud service fees to maintain the normal operation of the checkout system.

[0004] Option C: Native Mobile App + SQLite. Develop a standalone Android / iOS native app with a built-in SQLite database. While this option achieves zero cloud costs and offline availability, compared to the lightweight distribution model of mini-programs ("search and use instantly, open instantly via chat and sharing"), native apps require app store listings, face security warnings and blocking for unlisted apps, and have a cumbersome installation process. These factors significantly hinder acceptance, dissemination, and ease of use among small and micro-sized merchants.

[0005] Solution D of this invention (zero hardware, zero cloud fees, pure local JSON file read / write): Only requires the merchant's existing smartphone (¥0 additional hardware cost), runs directly within the mini-program (no need to download and install a separate app), and all product and transaction data are stored locally in a JSON file on the phone (zero cloud service fee). Full functionality is available even in offline environments. For micro-merchants, the startup cost is zero—simply search within the host application to begin POS operations. Table 1 compares the annual holding costs and key capabilities of the four solutions: Hardware costs ¥3000-8000 Requires basic hardware such as a computer or tablet. Existing smartphones Existing smartphones Annual cloud fees ¥0 ¥2400-6000 ¥0 ¥0 App installation required (POS software required) (POS software required) yes No (can be used directly within the host application) Available offline Yes (usually with a time limit, such as 90 days). no yes yes Data Engine SQLite (built-in) MySQL / Cloud DB SQLite Plain JSON + Adaptive Hash Index Applicable merchant size Medium and large Small and micro businesses Small and micro businesses Small and micro businesses The core design approach of the present invention, Scheme D, is to replace the commonly used core functions of traditional dedicated POS devices with the local computing and storage capabilities of the merchant's existing smartphones. Instead of pursuing comprehensive functionality, it focuses on frequently used operations in the POS scenario (scanning to check products, settlement and transaction records, normal operation even when offline, inventory / expiration warning, procurement and purchasing, printing, etc.), achieving the experience level of dedicated devices in these dimensions.

[0006] The core technical problem this invention aims to solve is: how to achieve the second-level lookup performance of Solution A and the data reliability of Solution B under the strict constraints of Solution D ("zero SQLite, pure JSON file read / write, and process can be killed at any time"), while maintaining the zero-cost advantage of Solution D. This is the substantial technical contribution of this invention.

[0007] In the simulated test, the present invention is designed for the extreme working conditions of the target user group. Referring to the aforementioned data on the operating scale of micro-merchants (average ≤200 transactions per day, SKU ≤2000 types), the test load is set to 10,000 types of products and 109,500 transactions per year (average 300 transactions per day × 365 days). Under these boundary conditions, it is ensured that: the QR code query response is not laggy (<1ms), the data write does not overflow (no backlog within a 100ms merging window), and the data is intact after the process is deactivated and restored.

[0008] (1) Unstructured database engine. Mini Programs do not provide embedded databases such as SQLite and IndexedDB. Developers can only persist data through the synchronous read / write interface (readFileSync / writeFileSync) of the file system module - which is essentially a conversion of "JavaScript object ↔ JSON string ↔ file". Developers need to design their own indexing and querying mechanisms.

[0009] (2) The process may be terminated by the system at any time. Unlike traditional desktop applications that are actively closed by the user, the process of a mini-program may be forcibly terminated by the system at any time—such as when the user switches apps, the screen is off for a long time, or there is insufficient memory. This means that the common approach of "writing to memory variables first and then flushing to disk later using an asynchronous timer" carries the risk of data loss: if the process is killed by the system before the timer is triggered, the changes that have not yet been persisted in memory will be lost forever.

[0010] (3) Synchronous file writing blocks the UI thread. writeFileSync is a synchronous blocking call, and each write takes 30-80ms. If synchronous writing is performed immediately every time a product is changed, it will accumulate into UI lag in continuous scanning scenarios.

[0011] There is a contradiction between constraint (2) and constraint (3): immediate synchronous writing → no data loss but UI lag; delayed asynchronous writing → smooth UI but data loss may occur when the process is about to be killed. This invention provides a double insurance solution of "delayed merging + background callback fallback" to address this contradiction. At the same time, delayed merging writing introduces a chain problem - inconsistency between the memory array and the disk file during the delay window → the hash index built based on the memory array may point to the wrong location - which leads to the necessity of barcode consistency verification in step S3 of this invention.

[0012] Non-patented references: [1] China Convenience Store Development Report 2025, KPMG China, June 2025, https: / / assets.kpmg.com / content / dam / kpmg / cn / pdf / zh / 2025 / 06 / china-convenience-store-development-report-2025.pdf Summary of the Invention

[0013] Corresponding to step S1—Constructing a product hash index. The product array is loaded from the persistent file into memory. The product array is traversed, and a hash mapping table is constructed using the barcode of each product as the key and its index in the array as the value. This mapping table is then cached in a module-level private variable. This hash mapping table reduces the time complexity of subsequent product queries from O(n) of fully traversing the array to a constant O(1) time, providing the index foundation for product queries in step S3.

[0014] The corresponding step S2 is merging writes and forced disk flushing. When product data changes, instead of immediately performing a blocking synchronous file write operation (because the synchronous writeFileSync call will block the JavaScript main thread, causing UI lag), the updated product array is temporarily stored in a module-level private variable. At the same time, a write timer with a preset delay duration (100 milliseconds) is started or reset. If the product data changes again during the timer's delay period, the updated product array temporarily stored in the private variable is updated and the timer is reset. This ensures that multiple changes during the delay period ultimately trigger only one file write operation, solving the technical problem of "frequent UI blocking during synchronous writes".

[0015] In this method, considering the environmental characteristic that the mini-program process may be terminated by the system at any time, a forced disk flushing function is registered in the background callback hook of the application lifecycle of the mini-program framework. When the application is detected to enter the background state, the forced disk flushing function performs the following operations: clearing the currently unexpired disk write timers, immediately writing the latest product array currently stored in the private variable to the persistent file through the synchronous file system interface, and triggering the mapping table reconstruction operation in step S4 after the write is completed. This forced disk flushing mechanism solves the technical problem of "data loss when the process is about to be killed".

[0016] The aforementioned merged write and forced disk flush together resolve the technical contradiction between "no lag" and "no data loss"—delayed merged write ensures smooth UI (normal path), while background callback forced disk flush ensures data security (backup path).

[0017] The corresponding step S3 is product query and consistency verification based on a hash mapping table. Upon receiving a query barcode, the system locates the index of the target product in the product array based on the hash mapping table constructed in step S1. A barcode consistency verification is then performed on the target product pointed to by this index—comparing the barcode field value of the target element with the query barcode. If they match, a match is returned (normally, this accounts for over 99.9% of stable POS scenarios with zero overhead); if they do not match, the hash mapping table is fully reconstructed using the current in-memory product array as the data source, and the target barcode is searched again in the reconstructed mapping table.

[0018] The necessity of barcode consistency verification in step S3 is directly driven by the technology choice in step S2. Step S2 employs a delayed merging strategy of "not writing immediately"—a 100ms delay timer is started when a product changes, during which multiple changes are merged into one, and the data is only written to disk after the timer expires. Within the 100ms window of the timer, the latest product array in memory (e.g., if a new product has just been added, the array length is increased by 1) is inconsistent with the products.json file on disk (which has not yet been updated). The hash mapping table is always built based on the memory array—if an insertion / deletion occurs in the array within the window, causing element index shifts, the index in the old mapping table will point to the wrong position. If step S2 is changed to "immediate synchronous writing upon change," there is no delay window between writing and index refreshing, the mapping table will not expire, and the above consistency verification mechanism will no longer be necessary. Therefore, the design decision of step S3 is directly driven by the technology choice in step S2, and there is a clear causal relationship between the two.

[0019] The fundamental difference between consistency checks and conventional cache checks. Conventional cache checks familiar to those skilled in the art—such as ETag / Last-Modified header comparison in web caching and dirty flags in memory caching—detect whether the content of cached data is expired (i.e., "whether the data in memory is the same as the data on disk"). This type of check targets the content state of the data, essentially answering "same value or not," and belongs to general caching techniques.

[0020] In this invention, the barcode consistency check in step S3 detects whether the structure of the hash mapping table has drifted—that is, whether "the index value in the mapping table is still consistent with the element position in the array." Its detection object is not the content of the product object (whether the price, inventory, or name has changed), but rather the internal consistency of the abstract data structure (barcode → index mapping). Specifically, it checks whether the barcode field of the element at the index position corresponding to a barcode in the mapping table constructed in step S1 is equal to the queried barcode—if not, it indicates that "this index now points to the wrong element" rather than "the value of this element has been updated." The reason for index drift is that the array has undergone insertion / deletion (the physical position of the element moves), which is unrelated to whether the element content has been updated (price changes, inventory changes).

[0021] The legal significance of this distinction lies in the fact that ETag / dirty tag verification addresses the "data expiration" problem (data layer), falling under the category of general caching technologies; while the barcode consistency verification in step S3 of this invention addresses the "data structure consistency" problem (structure layer)—the hash map table, as a secondary index structure built and manually maintained by the developer, requires the developer to guarantee its internal consistency (correctness of the index-element mapping), and no built-in API of the mini-program provides any guarantee for this. This is a unique technical issue arising from developers managing their own index structures in a pure JSON file read / write environment of the mini-program.

[0022] Why choose "full reconstruction" instead of "incremental update" as the recovery strategy after a consistency check failure? Within the delay window, the product array may simultaneously undergo insertion operations (inserting a new product at the middle of the array → incrementing the index of all elements after the insertion point by 1) and deletion operations (deleting a product from the array → decrementing the index of all elements after the deletion point by 1). If an incremental update strategy is adopted—that is, only updating the mapping relationship of changed entries—it is necessary to track the specific positions and sequences of all insertion and deletion operations within the window and calculate the net index offset of each affected entry. This tracking mechanism requires maintaining operation logs or version numbers, and its implementation complexity and maintenance cost are actually higher than full reconstruction. The full reconstruction strategy eliminates the complexity of incremental tracking by "abandoning tracking → direct reconstruction"—as described in claim 2, full reconstruction is only triggered when the barcode consistency check result is inconsistent (probability <0.1%), and the time complexity of each reconstruction is O(n) (n is the number of products). For tens of thousands of products, a single reconstruction takes about 1-2 milliseconds, and the overall performance overhead is negligible. This strategy of "replacing uncertain high-cost tracking with deterministic low-cost reconstruction" is directly driven by the multi-operational uncertainty of the delay window.

[0023] The corresponding step S4 is index synchronization and reconstruction. After each successful persistent write operation in step S2, the hash mapping table from step S1 is fully rebuilt using the latest written product array as the data source, ensuring consistency between the mapping table and the persistent data. Step S4 acts as a bridge between "writing" (step S2) and "querying" (step S3): the index is rebuilt immediately after each disk write, ensuring that the barcode consistency check in step S3 is performed based on an index consistent with the persistent file during the next query, eliminating the cumulative impact of the delay window in step S2 on subsequent queries.

[0024] The technical constraints between each step. The four steps described above form a complete problem-solving chain: S1 (Building a product hash index) → Provides the basis for O(1) queries for S3 ↓ S2 (Merge Write and Forced Disk Flush) → Resolves "UI lag" and "data loss", but introduces "indexes within the delay window may expire". ↓ S3 (Product Query and Consistency Check) → Resolves "index expiration" issues, ensuring queries are always correct. ↓ S4 (Index Synchronous Reconstruction) → After each disk write, it corrects the impact of the S2 delay window on the index, forming a closed loop. Overall beneficial effects of the present invention: (1) It resolves the technical contradiction between "no lag" and "no data loss". The delayed merging write in step S2 ensures smooth UI (normal path), and the background callback forces disk flushing to ensure data security (backup path).

[0025] (2) The barcode consistency verification in step S3 is an integral part of the delayed write strategy in step S2. It eliminates the "index drift" side effect caused by delayed write, and there is a clear causal relationship between the two.

[0026] (3) The essential difference between the consistency check in step S3 and the general cache check lies in the object being checked. The general cache check (ETag / dirty mark) checks whether the data content is expired (data layer); the consistency check in step S3 of this invention checks the internal consistency of the abstract data structure (barcode → index mapping) (structure layer), which is a unique technical problem of the secondary index structure built and maintained by the developer.

[0027] (4) A data engine for O(1) lookup of tens of thousands of products was implemented under the condition of zero hardware cost without a database engine and only synchronizing file API. Under extreme test conditions (test equipment: Redmi Note 12 low-end smartphone launched in 2022; operating environment: mini program; test data source: simulated data generated by Python offline script generate_mock_data.py, configured product_count=10000, total_days=365, orders_per_day=300 and then imported into the mini program), the specific characteristics of the test data are: 10,000 products, barcodes are 13-digit EAN-13 standard format (prefix is ​​fixed as 69, the following 10 digits are random numbers, and the last digit is the calculated value of EAN-13 check digit); the product name is composed of brand name (2-3 middle The product name is composed of Chinese characters (from 67 brand material libraries) and category words (2-4 Chinese characters, from about 80 category material libraries). There is about a 40% probability that a packaging specification string (such as "500ml" or "100g") will be appended to the end. The name has an average of about 7 Chinese characters. Each product has 14 fields. Among them, the productionDate and expiryDate fields are always empty strings, the supplier and description fields are each about 75% likely to be empty strings, and the remaining 10 fields are non-empty. Under these data characteristics, using the consistency verification logic as described in claim 2 (triggering a full reconstruction only when there is inconsistency), the time taken for a single barcode query in the hash index hit path is less than 1 millisecond; under the same load of 10,000 products, the time taken for a single full index reconstruction (traversing all products to regenerate barcodes → index mapping table) is 8 to 15 milliseconds (depending on the device's CPU performance); combined with a hash index hit rate of over 99.9%, meaning that at most one full reconstruction is triggered only every 1,000 or more queries, under the 100-millisecond preset duration as described in claim 3, the total time taken for the complete checkout process (scanning to check products → settlement and writing transaction records → delayed disk write → index update) is far lower than the user's perceived threshold.

[0028] (5) Data reliability verification under abnormal scenarios. In the simulation test, the following process was executed 100 times: the application completes the cashier settlement (the latest product array and transaction record are temporarily stored in memory, and the 100-millisecond timer described in claim 3 has not yet been triggered to write to disk) → simulate system deactivation (forcefully terminate the application process) → restart the application → read the persistent JSON file → verify the integrity of the product inventory data and transaction record. In the 100 tests, there was zero data loss and zero data corruption, proving that the forced disk flushing mechanism detected when the application enters the background state in step S2 effectively solves the technical problem of "data loss when the process is about to be killed". Detailed Implementation

[0029] Example 1: Construction, querying, and consistency verification of product hash index (corresponding to steps S1+S3) `buildBarcodeIndex` iterates through the product array, constructing a hash map (cached by the module-level closure variable `_barcodeIndex`) using barcodes as keys and array indices as values. `getProductByBarcode` receives the query barcode, locates the target product index based on the hash map, and performs a barcode consistency check—if the barcodes match, a match is returned (normally, this occurs in >99.9% of cases); if the barcodes do not match, a full reconstruction is performed and the query is repeated. The `products` parameter passed during the call is always the latest product array in memory. As described in claim 2, a full reconstruction is only triggered when the barcode consistency check result is inconsistent.

[0030] Numerical example of index drift. Taking 5 items as an example, the specific process of detecting index drift in barcode consistency verification in S3 of claim 1 is explained.

[0031] Assume the initial state of the product array `products` and the hash map `_barcodeIndex`: products: [{barcode:"692000000001"},{barcode:"692000000002"},{barcode:"692000000003"},{barcode:"692000000004"},{barcode:"692000000005"}] _barcodeIndex: "692000000001"→0, "692000000002"→1, "692000000003"→2, "692000000004"→3, "692000000005"→4 Operation sequence: ① The cashier scans the barcode "692000000005" (battery) → verification successful → triggers debouncedWriteProducts → the 100-millisecond timer as described in claim 3 starts. ② The inventory administrator adds the product "Chocolate" (barcode "692000000006", appended to the end of the array at index 5). ③ The administrator deletes the product "Milk" (originally at index 2).

[0032] At this point, the latest array in memory has become ("tissue" moved from index 3 to index 2, "battery" moved from index 4 to index 3, and "chocolate" is at index 4), but _barcodeIndex has not yet been rebuilt: Products (latest memory): [0] Mineral water [1] Bread [2] Tissues [3] Battery [4] Chocolate _barcodeIndex (when expired): "692000000003"→2 (Deleted!) "692000000004"→3 (Drifted!) "692000000005"→4 (Drifted!) If the cashier scans the code "692000000005" (battery), the expiration mapping table takes index 4 → products[4] is now "chocolate" instead of "battery"! The consistency check (products[4].barcode !== "692000000005") fails → triggering a full rebuild.

[0033] This example demonstrates that a single insertion followed by a deletion results in 3 out of 5 mapped items becoming invalid. This is precisely the technical reason for "choosing full reconstruction over incremental tracking"—under multiple compound operations, incremental tracking requires recording "deleted position = 2, added position = 5" and calculating "net offset of items with index ≥ 3 = -1", which is more expensive than performing a full reconstruction on all 5 items.

[0034] Example 2: Merging write, forced flush and index synchronous reconstruction (corresponding to steps S2+S4) The `debouncedWriteProducts` function temporarily stores the latest product array in the module-level private variable `_pendingProducts`, starts / resets the 100-millisecond delay timer as described in claim 3, and performs a persistent write operation via `writeJSON` after the timer expires (merging all changes within the window period). After successful writing, it calls `buildBarcodeIndex` to fully rebuild the hash mapping table (corresponding to step S4).

[0035] The forced flush function `flushProductWrite` is registered in the background callback hook (`onHide`) of the mini-program application lifecycle. When the application is detected to be in the background, it executes the following: clearing the currently unexpired delayed timers (`clearTimeout`) → immediately writing `_pendingProducts` to the persistent file via `writeJSON` → calling `buildBarcodeIndex` to fully rebuild the hash mapping table → setting both timer references and temporary data references to null.

[0036] Normal cashier √ Disk after 100ms — √ Rapidly scan multiple items in a continuous manner √ Merge into a single write — √ Answer the phone / switch to the app immediately after checkout. X timer has not expired. √ Intercept and drop onto disk √ Example 3: Compact persistent writing (corresponding to claim 4) The `stripEmpty` function recursively traverses the data to be written: for object type nodes, it iterates through all attribute keys, removing attributes with values ​​of empty strings, null, or undefined; for array type nodes, it recursively performs the same removal process on each element. The `writeJSON` function serves as the sole proxy entry point for all calls to the synchronous file write interface to perform persistence operations—before calling the synchronous file write interface for serialization, it first performs `stripEmpty` on the data parameters to remove empty attributes. Under extreme testing conditions (10,000 products, each containing 14 attributes, of which 4 attributes have approximately a 75% probability of being empty), `stripEmpty` processing reduces the size of the persistent JSON file by approximately 30%, thereby shortening the file system time occupied by each disk write operation within the 100-millisecond latency window as described in claim 3.

[0037] In addition, writeJSON has a built-in exception recovery mechanism: when the synchronous file write interface throws an exception due to insufficient storage space, it automatically reads the storage policy configuration issued by the backend, calls the tiered cleanup function in pressure cleanup mode (retaining at least 6 months of data) to release storage space, and then retryes the write; if the retry still fails, an error log is output. This mechanism enables persistent write operations to have self-healing capabilities even when storage space is critical, avoiding data loss due to a single write failure.

[0038] Example 4: Monthly Sharded Storage and Loading (corresponding to claim 5) Transaction data is stored in segments by calendar month—detail files are named YYYY-MM.json (e.g., 2026-05.json) and stored in the sales / details / directory; a monthly summary file, sales / index_total.json (with a constant size of KB), is also maintained. The initial report view only loads the monthly summary file to complete the hash index construction and basic report rendering. When a user triggers a scrolling action to view details, the corresponding monthly shard files are loaded as needed. This sharding and lazy loading mechanism separates the transaction data loading operation from the hash index construction operation in step S1 in time—only the constant-size summary file is loaded on the initial view, and detailed data is loaded as needed after a user triggers a scrolling action, avoiding the initial construction of the hash mapping table being blocked due to excessive JSON parsing time during full data synchronous loading.

[0039] Example 5: Automatic cleanup of expired data (corresponding to claim 6) Seven cleanup functions, including `cleanupOldStockRecords` and `cleanupOldSalesDetails`, automatically clean up expired data files. This is triggered every time the mini-program starts up (the storage cleanup function is called during the application lifecycle callback). The cleanup logic utilizes the YYYY-MM.json naming convention of the monthly sharded files, validates the filename format using the regular expression ` / ^\d{4}-\d{2}$ / `, and locates expired files exceeding their retention period (configured by the backend storage policy, defaulting to 37 calendar months) by comparing filenames in lexicographical order, then deletes them. This cleanup operation is performed during the cold start phase, naturally isolated from high-frequency runtime operations such as product queries and payment settlements. This avoids the IO operations generated by file deletion competing with barcode queries in step S1 and delayed writes in step S2 for file system resources. When storage usage exceeds a preset threshold (180MB), it automatically switches to a pressure cleanup mode—deleting data month by month starting from the oldest month until storage usage drops below the threshold.

[0040] Example 6: Construction, querying, and consistency verification of arbitrary key-value indexes (corresponding to claims 8-10) This embodiment illustrates how the index construction and maintenance mechanism in steps S1-S4 of claim 1 can be extended from a single mapping table of product barcode → index to a key-value mapping table system with any data field as the key.

[0041] (1) Sales Aggregation Index. Corresponding to the sales aggregation index described in claim 9. In the cashier settlement confirmation process, the system maintains a key-value index file sales / index_products / YYYY-MM.json, which is sharded by month: the product barcode is used as the key, and the aggregation object (containing product name, sales volume, sales amount, cost, and profit) is used as the value. Each time settlement is performed, each product in the order is traversed—the corresponding aggregation object is located using the barcode as the key: if the key does not exist, the aggregation object is initialized; if it exists, the sales volume, sales amount, cost, and profit are accumulated. The write operation is uniformly executed through the compact persistent proxy described in claim 4, and the write is delayed to disk by the merge write timer described in claim 2. When the report query requests the index, the system loads it from the disk and performs the same consistency check as step S3—the product name field in the aggregation object is checked against the name in the current product array: if they match, a hit is returned; if they do not match (such as name mismatch caused by a delay window between index writing and product renaming), the key-value index is fully rebuilt using the current product array as the data source, and the query is responded to again.

[0042] (2) Cross-shard summary index. Corresponding to the cross-shard summary index described in claim 10. On top of the above-mentioned monthly sharded sales aggregation index, the system additionally maintains a summary index file sales / index_total.json with a constant total volume: using the month identifier (YYYY-MM format) as the key and the summary statistics for that month (including the number of orders, sales, costs, and profits) as the value. This summary index is independent of each monthly shard file, and its volume does not increase with the transaction volume—always maintaining one record per month. The first screen of the report interface only loads this summary index (a constant volume of several KB) to complete the hash index construction and basic report rendering, without loading the detailed shards for each month; when the user triggers the scrolling to view the details operation, the corresponding monthly shard is loaded as needed, realizing the separation of data loading in step S1' and hash index construction in step S1 in terms of time.

[0043] (3) Purchase Order Index. The system maintains purchase_orders / _index.json as a key-value mapping table for purchase orders: the order ID is the key, and the order summary object (containing order name, creation time, total amount, and arrival status) is the value. When creating a new order, this index is updated first (adding or overwriting key-value pairs), and then persistence is performed through a unified write agent. When querying the order list, only this index is loaded to render the order overview, and detailed data is loaded as needed after the user clicks on a specific order.

[0044] (4) Generalization of consistency verification. All three key-value mapping tables mentioned above adopt the same verification-reconstruction mechanism as step S3: each query based on the key-value mapping table performs a consistency verification of the identifier field (the sales aggregate index verifies the product name field, the summary index verifies the consistency of the cumulative number of orders and sales amount, and the order index verifies the consistency of the order identifier) ​​- if the verification passes, a hit is returned; if the verification fails, the index is fully reconstructed with the current in-memory data source and the query is re-queried. This verification-reconstruction mechanism is a generalized extension of step S3 in claim 1 in the key-value mapping table scenario. Its technical essence - "replacing the full-process uncertainty tracking with a single deterministic O(1) verification" - does not change due to different key types or value structures. Attached Figure Description

[0045] Figure 1 This diagram illustrates the technical constraints of steps S1 to S4 of the present invention. It shows how the delayed merge write decision in step S2 drives the generation of the consistency verification mechanism in step S3, and how step S4 forms a closed-loop repair complete logical link under the constraints of an operating environment where there is no database engine, only synchronized file APIs, and processes may be deactivated by the system at any time.

[0046] Figure 2This is a flowchart of the hash index query and adaptive consistency verification in steps S1 and S3 of the present invention. It includes the path for locating the array index based on the hash mapping table after the barcode query request is received, the direct hit return path when the barcode consistency verification is successful, and the recovery path for triggering a full reconstruction of the mapping table and re-searching when the verification fails (index drift).

[0047] Figure 3 This is a timing diagram of the dual-insurance mechanism of merged writing and forced disk flushing via background callback in step S2 of the present invention. It shows the normal disk flushing path of merged writing within the delay window after the product data is changed, and the fallback disk flushing path of truncating the timer before it expires and immediately executing synchronous writing when the application enters the background state through background lifecycle callback.

[0048] Figure 4 This is a schematic diagram of the compact write agent structure of the present invention, showing that each business module, such as the delayed write module, the sharded write module, and the backup export module, performs persistence operations through a unified write agent. Before performing synchronous file writing, the agent recursively removes empty attributes (empty strings, null, undefined) from the data, then serializes it into JSON and writes it to the file system.

[0049] Figure 5 This is a flowchart illustrating the monthly sharded storage and two-level lazy loading mechanism of the present invention. It shows that the first screen of the report only loads the monthly summary index file with a constant size to complete the basic rendering, and the detailed data is loaded as needed after the user triggers the scrolling operation, which is a loading separation strategy.

[0050] Figure 6 This is a flowchart of the cold start triggering and layered cleanup in the automatic expired data cleanup mechanism of the present invention. It shows the strategy of triggering the cleanup operation when the mini program is cold started and isolating it from high-frequency running paths such as cashier settlement and product query, as well as the branch logic between the normal cleanup mode and the pressure cleanup mode that switches when the storage usage exceeds the preset threshold.

Claims

1. An adaptive hash index storage and fast retrieval method for a mini-program POS system An adaptive hash index storage and fast retrieval method for a mini-program POS system, applicable to runtime environments that do not provide a structured database engine, use a synchronous file system interface for data persistence, and where application processes may be terminated by the system at any time, is characterized by including the following steps: Step S1, Construct a product hash index: Load the product array from the persistent file into memory, generate a hash mapping table using the barcode of each product as the key and the index of the product in the array as the value, and cache it; Step S2, Merge Write and Forced Disk Flush: When product data changes, the updated product array is temporarily stored in a private variable, and a preset delay timer is started or reset; after the delay timer expires, the updated product array in the private variable is persistently written; and when the application is detected to enter the background state, the delay timer is cleared, and the updated product array in the private variable is persistently written immediately. Step S3, Product query and consistency verification based on the hash mapping table: Receive a query barcode, locate the index of the target product in the product array based on the hash mapping table; verify whether the barcode of the target product pointed to by the index is consistent with the query barcode; if consistent, return the target product; if inconsistent, rebuild the hash mapping table in its entirety using the product array as the data source, and search for the query barcode again after reconstruction; Step S4, Index Synchronization Reconstruction: After each successful persistent write operation, the hash mapping table is fully reconstructed using the latest written product array as the data source.

2. The method according to claim 1 Its features are, In step S3, the logic for triggering a full reconstruction is as follows: when the index corresponding to the query barcode exists in the hash mapping table, the target product is located and the verification is performed; the full reconstruction is only performed when the verification result is inconsistent.

3. The method according to claim 1 Its features are, The preset duration is 100 milliseconds; in step S2, the operation of immediately performing persistent writing includes: clearing the delay timer, calling the synchronous file writing function to execute the write to disk, calling the mapping table reconstruction function, and setting the timer reference and the temporary data reference to null.

4. The method according to claim 1 Its features are, Before each persistent write operation, a compact persistence step is included, which recursively removes null properties: for the latest temporary product array, all properties of each product object are traversed, and properties with values ​​of empty strings, null, or undefined are removed; the product array after removal is serialized into a persistent format and written to a file.

5. The method according to claim 1 Its features are, It also includes the steps of sharding and loading transaction data: sharding and storing transaction data into independent monthly shard files according to natural months; maintaining a monthly summary file with a constant total volume; when loading the report interface, only the monthly summary file is loaded on the first screen to complete the hash index construction and basic report rendering; when the user triggers the operation of scrolling to view details, the corresponding monthly shard file is loaded as needed.

6. The method according to claim 5 Its features are, It also includes an automatic cleanup step based on the naming rules of the segmented files: using the naming rules of the monthly segmented files, expired files that have exceeded the preset retention period are located by string comparison and deleted; the location and deletion operations are triggered on the user's low-frequency operation path and are isolated from the high-frequency operation paths of product query and payment settlement.

7. An adaptive hash index storage and fast retrieval system for a mini-program POS system An adaptive hash index storage and fast retrieval system for a mini-program POS system, applicable to an operating environment that does not provide a structured database engine, uses a synchronous file system interface as the data persistence method, and where the application process may be terminated by the system at any time, characterized in that... include: The data loading and index building unit is used to load the product array from the persistent file into memory, and build and cache a hash mapping table with barcode as the key and array subscript as the value; The write throttling and forced flush module is used to temporarily store the latest product array when product data changes, merge multiple changes through a resettable delay timer to perform a single persistent write; and, when the application is detected to be in the background, the timer is truncated and the persistent write of the temporarily stored data is immediately performed. An adaptive hash index module is used to locate the target product and perform barcode consistency verification based on the hash mapping table during each query. If the verification fails, the hash mapping table will be fully rebuilt using the current in-memory product array as the data source, and the query will be performed again. The index synchronization module is used to trigger a full reconstruction of the hash map table after each successful persistent write.

8. The method according to claim 1 Its features are, The hash mapping table constructed in step S1 uses the product barcode as the key and the array index as the value; the method is also applicable to the construction and maintenance of key-value mapping tables that use any data field as the key and the aggregated statistical value associated with that data item as the value, including: Step S1': Construct a key-value mapping table: Load the data set from the specified persistent file into memory, generate a key-value mapping table with the specified field value of each record in the data set as the key and the target aggregation field set of the record as the value, and cache it. Step S3', query and consistency verification based on the key-value mapping table: receive a query key, locate the corresponding aggregate value based on the key-value mapping table; verify whether the identifier field in the aggregate value is consistent with the query key - if consistent, return the hit; if inconsistent, rebuild the key-value mapping table in full using the current memory copy of the data set as the data source and then query again. Step S4', Key-value mapping table synchronous reconstruction: After each successful persistent write operation to the data set, the key-value mapping table is fully reconstructed using the latest written data set as the data source.

9. The method according to claim 8 Its features are, The key-value mapping table is a sales aggregation index: Use the product barcode as the key and the aggregate object containing cumulative sales volume, cumulative sales revenue, cumulative cost, and cumulative profit as the value; The sales aggregation index is updated each time a checkout is confirmed—by locating the corresponding aggregation object using the product barcode in the order, accumulating the sales quantity, sales amount, cost, and profit of that product, and then writing it back. The persistent file of the sales aggregate index is stored in shards by natural month, and each shard file independently maintains a key-value mapping table.

10. The method according to claim 8 Its features are, The key-value mapping table is stored in shards according to the time dimension, and the persistent file corresponding to each shard is named in the format YYYY-MM.json; it also includes locating and deleting expired index shards that exceed the preset retention period based on the naming rules of the shard files; In addition, a cross-shard summary index file with a constant total volume is maintained. This summary index file uses the month identifier as the key and the aggregated statistical value of that month as the value, so that the first screen rendering can be completed by reading the summary index file when loading the page.