diff --git a/best-practices-on-public-cloud.md b/best-practices-on-public-cloud.md deleted file mode 100644 index 33f95c71cdcb0..0000000000000 --- a/best-practices-on-public-cloud.md +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: TiDB Best Practices on Public Cloud -summary: Learn about the best practices for deploying TiDB on public cloud. ---- - -# TiDB Best Practices on Public Cloud - -Public cloud infrastructure has become an increasingly popular choice for deploying and managing TiDB. However, deploying TiDB on public cloud requires careful consideration of several critical factors, including performance tuning, cost optimization, reliability, and scalability. - -This document covers various essential best practices for deploying TiDB on public cloud, such as reducing compaction I/O flow in KV RocksDB, using a dedicated disk for Raft Engine, optimizing costs for cross-AZ traffic, mitigating Google Cloud live migration events, and fine-tuning the PD server in large clusters. By following these best practices, you can maximize the performance, cost efficiency, reliability, and scalability of your TiDB deployment on public cloud. - -## Reduce compaction I/O flow in KV RocksDB - -As the storage engine of TiKV, [RocksDB](https://rocksdb.org/) is used to store user data. Because the provisioned IO throughput on cloud EBS is usually limited due to cost considerations, RocksDB might exhibit high write amplification, and the disk throughput might become the bottleneck for the workload. As a result, the total number of pending compaction bytes grows over time and triggers flow control, which indicates that TiKV lacks sufficient disk bandwidth to keep up with the foreground write flow. - -To alleviate the bottleneck caused by limited disk throughput, you can improve performance by [enabling Titan](#enable-titan). If your average row size is smaller than 512 bytes, Titan is not applicable. In this case, you can improve performance by [increasing all the compression levels](#increase-all-the-compression-levels). - -### Enable Titan - -[Titan](/storage-engine/titan-overview.md) is a high-performance [RocksDB](https://github.com/facebook/rocksdb) plugin for key-value separation, which can reduce write amplification in RocksDB when large values are used. - -If your average row size is larger than 512 bytes, you can enable Titan to reduce the compaction I/O flow as follows, with `min-blob-size` set to `"512B"` or `"1KB"` and `blob-file-compression` set to `"zstd"`: - -```toml -[rocksdb.titan] -enabled = true -[rocksdb.defaultcf.titan] -min-blob-size = "1KB" -blob-file-compression = "zstd" -``` - -> **Note:** -> -> When Titan is enabled, there might be a slight performance degradation for range scans on the primary key. For more information, see [Impact of `min-blob-size` on performance](/storage-engine/titan-overview.md#impact-of-min-blob-size-on-performance). - -### Increase all the compression levels - -If your average row size is smaller than 512 bytes, you can increase all the compression levels of the default column family to `"zstd"` as follows: - -```toml -[rocksdb.defaultcf] -compression-per-level = ["zstd", "zstd", "zstd", "zstd", "zstd", "zstd", "zstd"] -``` - -## Use a dedicated disk for Raft Engine - -The [Raft Engine](/glossary.md#raft-engine) in TiKV plays a critical role similar to that of a write-ahead log (WAL) in traditional databases. To achieve optimal performance and stability, it is crucial to allocate a dedicated disk for the Raft Engine when you deploy TiDB on public cloud. The following `iostat` shows the I/O characteristics on a TiKV node with a write-heavy workload. - -``` -Device r/s rkB/s w/s wkB/s f/s aqu-sz %util -sdb 1649.00 209030.67 1293.33 304644.00 13.33 5.09 48.37 -sdd 1033.00 4132.00 1141.33 31685.33 571.00 0.94 100.00 -``` - -The device `sdb` is used for KV RocksDB, while `sdd` is used to restore Raft Engine logs. Note that `sdd` has a significantly higher `f/s` value, which represents the number of flush requests completed per second for the device. In Raft Engine, when a write in a batch is marked synchronous, the batch leader will call `fdatasync()` after writing, guaranteeing that buffered data is flushed to the storage. By using a dedicated disk for Raft Engine, TiKV reduces the average queue length of requests, thereby ensuring optimal and stable write latency. - -Different cloud providers offer various disk types with different performance characteristics, such as IOPS and MBPS. Therefore, it is important to choose an appropriate cloud provider, disk type, and disk size based on your workload. - -### Choose appropriate disks for Raft Engine on public clouds - -This section outlines best practices for choosing appropriate disks for Raft Engine on different public clouds. Depending on performance requirements, two types of recommended disks are available. - -#### Middle-range disk - -The following are recommended middle-range disks for different public clouds: - -- On AWS, [gp3](https://aws.amazon.com/ebs/general-purpose/) is recommended. The gp3 volume offers a free allocation of 3000 IOPS and 125 MB/s throughput, regardless of the volume size, which is usually sufficient for the Raft Engine. - -- On Google Cloud, [pd-ssd](https://cloud.google.com/compute/docs/disks#disk-types/) is recommended. The IOPS and MBPS vary depending on the allocated disk size. To meet performance requirements, it is recommended to allocate 200 GB for Raft Engine. Although Raft Engine does not require such a large space, it ensures optimal performance. - -- On Azure, [Premium SSD v2](https://learn.microsoft.com/en-us/azure/virtual-machines/disks-types#premium-ssd-v2) is recommended. Similar to AWS gp3, Premium SSD v2 provides a free allocation of 3000 IOPS and 125 MB/s throughput, regardless of the volume size, which is usually sufficient for Raft Engine. - -#### High-end disk - -If you expect an even lower latency for Raft Engine, consider using high-end disks. The following are recommended high-end disks for different public clouds: - -- On AWS, [io2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html) is recommended. Disk size and IOPS can be provisioned according to your specific requirements. - -- On Google Cloud, [pd-extreme](https://cloud.google.com/compute/docs/disks#disk-types/) is recommended. Disk size, IOPS, and MBPS can be provisioned, but it is only available on instances with more than 64 CPU cores. - -- On Azure, [ultra disk](https://learn.microsoft.com/en-us/azure/virtual-machines/disks-types#ultra-disks) is recommended. Disk size, IOPS, and MBPS can be provisioned according to your specific requirements. - -### Example 1: Run a social network workload on AWS - -AWS offers 3000 IOPS and 125 MBPS/s for a 20 GB [gp3](https://aws.amazon.com/ebs/general-purpose/) volume. - -By using a dedicated 20 GB [gp3](https://aws.amazon.com/ebs/general-purpose/) Raft Engine disk on AWS for a write-intensive social network application workload, the following improvements are observed but the estimated cost only increases by 0.4%: - -- a 17.5% increase in QPS (queries per second) -- an 18.7% decrease in average latency for insert statements -- a 45.6% decrease in p99 latency for insert statements. - -| Metric | Shared Raft Engine disk | Dedicated Raft Engine disk | Difference (%) | -| ------------- | ------------- |------------- |------------- | -| QPS (K/s)| 8.0 | 9.4 | 17.5| -| AVG Insert Latency (ms)| 11.3 | 9.2 | -18.7 | -| P99 Insert Latency (ms)| 29.4 | 16.0 | -45.6| - -### Example 2: Run TPC-C/Sysbench workload on Azure - -By using a dedicated 32 GB [ultra disk](https://learn.microsoft.com/en-us/azure/virtual-machines/disks-types#ultra-disks) for Raft Engine on Azure, the following improvements are observed: - -- Sysbench `oltp_read_write` workload: a 17.8% increase in QPS and a 15.6% decrease in average latency. -- TPC-C workload: a 27.6% increase in QPS and a 23.1% decrease in average latency. - -| Metric | Workload | Shared Raft Engine disk | Dedicated Raft Engine disk | Difference (%) | -| ------------- | ------------- | ------------- |------------- |------------- | -| QPS (K/s) | Sysbench `oltp_read_write` | 60.7 | 71.5 | 17.8| -| QPS (K/s) | TPC-C | 23.9 | 30.5 | 27.6| -| AVG Latency (ms)| Sysbench `oltp_read_write` | 4.5 | 3.8 | -15.6 | -| AVG Latency (ms)| TPC-C | 3.9 | 3.0 | -23.1 | - -### Example 3: Attach a dedicated pd-ssd disk on Google Cloud for Raft Engine on TiKV manifest - -The following TiKV configuration example shows how to attach an additional 512 GB [pd-ssd](https://cloud.google.com/compute/docs/disks#disk-types/) disk to a cluster on Google Cloud deployed by [TiDB Operator](https://docs.pingcap.com/tidb-in-kubernetes/stable), with `raft-engine.dir` configured to store Raft Engine logs to this specific disk. - -``` -tikv: - config: | - [raft-engine] - dir = "/var/lib/raft-pv-ssd/raft-engine" - enable = true - enable-log-recycle = true - requests: - storage: 4Ti - storageClassName: pd-ssd - storageVolumes: - - mountPath: /var/lib/raft-pv-ssd - name: raft-pv-ssd - storageSize: 512Gi -``` - -## Optimize cost for cross-AZ network traffic - -Deploying TiDB across multiple availability zones (AZs) can lead to increased costs due to cross-AZ data transfer fees. To optimize costs, it is important to reduce cross-AZ network traffic. - -To reduce cross-AZ read traffic, you can enable the [Follower Read feature](/follower-read.md), which allows TiDB to prioritize selecting replicas in the same availability zone. To enable this feature, set the [`tidb_replica_read`](/system-variables.md#tidb_replica_read-new-in-v40) variable to `closest-replicas` or `closest-adaptive`. - -To reduce network traffic caused by the data shuffle of TiFlash MPP tasks, it is recommended to deploy multiple TiFlash instances in the same availability zones (AZs). Starting from v6.6.0, [compression exchange](/explain-mpp.md#mpp-version-and-exchange-data-compression) is enabled by default, which reduces the network traffic caused by MPP data shuffle. - -## Mitigate live migration maintenance events on Google Cloud - -The [Live Migration feature](https://cloud.google.com/compute/docs/instances/live-migration-process) of Google Cloud enables VMs to be seamlessly migrated between hosts without causing downtime. However, these migration events, although infrequent, can significantly impact the performance of VMs, including those running in a TiDB cluster. During such events, affected VMs might experience reduced performance, leading to longer query processing times in the TiDB cluster. - -To detect live migration events initiated by Google Cloud and mitigate the performance impact of these events, TiDB provides a [watching script](https://github.com/PingCAP-QE/tidb-google-maintenance) based on Google's metadata [example](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/compute/metadata/main.py). You can deploy this script on TiDB, TiKV, and PD nodes to detect maintenance events. When a maintenance event is detected, appropriate actions can be taken automatically as follows to minimize disruption and optimize the cluster behavior: - -- TiDB: Takes the TiDB node offline by cordoning it and deleting the TiDB pod. This assumes that the node pool of the TiDB instance is set to auto-scale and dedicated to TiDB. Other pods running on the node might experience interruptions, and the cordoned node is expected to be reclaimed by the auto-scaler. -- TiKV: Evicts leaders on the affected TiKV store during maintenance. -- PD: Resigns a leader if the current PD instance is the PD leader. - -It is important to note that this watching script is specifically designed for TiDB clusters deployed using [TiDB Operator](https://docs.pingcap.com/tidb-in-kubernetes/dev/tidb-operator-overview), which offers enhanced management functionalities for TiDB in Kubernetes environments. - -By utilizing the watching script and taking necessary actions during maintenance events, TiDB clusters can better handle live migration events on Google Cloud and ensure smoother operations with minimal impact on query processing and response times. - -## Tune PD for a large-scale TiDB cluster with high QPS - -In a TiDB cluster, a single active Placement Driver (PD) server is used to handle crucial tasks such as serving the TSO (Timestamp Oracle) and processing requests. However, relying on a single active PD server can limit the scalability of TiDB clusters. - -### Symptoms of PD limitation - -The following diagrams show the symptoms of a large-scale TiDB cluster consisting of three PD servers, each equipped with 56 CPUs. From these diagrams, it is observed that when the query per second (QPS) exceeds 1 million and the TSO (Timestamp Oracle) requests per second exceed 162,000, the CPU utilization reaches approximately 4,600%. This high CPU utilization indicates that the PD leader is experiencing a significant load and is running out of available CPU resources. - -![pd-server-cpu](/media/performance/public-cloud-best-practice/baseline_cpu.png) -![pd-server-metrics](/media/performance/public-cloud-best-practice/baseline_metrics.png) - -### Tune PD performance - -To address the high CPU utilization issue in the PD server, you can make the following tuning adjustments: - -#### Adjust PD configuration - -[`tso-update-physical-interval`](/pd-configuration-file.md#tso-update-physical-interval): This parameter controls the interval at which the PD server updates the physical TSO batch. By reducing the interval, the PD server can allocate TSO batches more frequently, thereby reducing the waiting time for the next allocation. - -``` -tso-update-physical-interval = "10ms" # default: 50ms -``` - -#### Adjust a TiDB global variable - -In addition to the PD configuration, enabling the TSO client batch wait feature can further optimize the TSO client's behavior. To enable this feature, you can set the global variable [`tidb_tso_client_batch_max_wait_time`](/system-variables.md#tidb_tso_client_batch_max_wait_time-new-in-v530) to a non-zero value. - -``` -set global tidb_tso_client_batch_max_wait_time = 2; # default: 0 -``` - -#### Adjust TiKV configuration - -To reduce the number of Regions and alleviate the heartbeat overhead on the system, you can refer to [Adjust Region size](/best-practices/massive-regions-best-practices.md#method-6-adjust-region-size) to moderately increase the size of the Region in TiKV configuration. - -``` -[coprocessor] - region-split-size = "288MiB" -``` - -### After tuning - -After the tuning, the following effects can be observed: - -- The TSO requests per second are decreased to 64,800. -- The CPU utilization is significantly reduced from approximately 4,600% to 1,400%. -- The P999 value of `PD server TSO handle time` is decreased from 2ms to 0.5ms. - -These improvements indicate that the tuning adjustments have successfully reduced the CPU utilization of the PD server while maintaining stable TSO handling performance. - -![pd-server-cpu](/media/performance/public-cloud-best-practice/after_tuning_cpu.png) -![pd-server-metrics](/media/performance/public-cloud-best-practice/after_tuning_metrics.png) diff --git a/best-practices/java-app-best-practices.md b/best-practices/java-app-best-practices.md deleted file mode 100644 index 987628c8e4413..0000000000000 --- a/best-practices/java-app-best-practices.md +++ /dev/null @@ -1,414 +0,0 @@ ---- -title: Best Practices for Developing Java Applications with TiDB -summary: This document introduces best practices for developing Java applications with TiDB, covering database-related components, JDBC usage, connection pool configuration, data access framework, Spring Transaction, and troubleshooting tools. TiDB is highly compatible with MySQL, so most MySQL-based Java application best practices also apply to TiDB. ---- - -# Best Practices for Developing Java Applications with TiDB - -This document introduces the best practice for developing Java applications to better use TiDB. Based on some common Java application components that interact with the backend TiDB database, this document also provides the solutions to commonly encountered issues during development. - -## Database-related components in Java applications - -Common components that interact with the TiDB database in Java applications include: - -- Network protocol: A client interacts with a TiDB server via the standard [MySQL protocol](https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html). -- JDBC API and JDBC drivers: Java applications usually use the standard [JDBC (Java Database Connectivity)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) API to access a database. To connect to TiDB, you can use a JDBC driver that implements the MySQL protocol via the JDBC API. Such common JDBC drivers for MySQL include [MySQL Connector/J](https://github.com/mysql/mysql-connector-j) and [MariaDB Connector/J](https://mariadb.com/kb/en/library/about-mariadb-connector-j/#about-mariadb-connectorj). -- Database connection pool: To reduce the overhead of creating a connection each time it is requested, applications usually use a connection pool to cache and reuse connections. JDBC [DataSource](https://docs.oracle.com/javase/8/docs/api/javax/sql/DataSource.html) defines a connection pool API. You can choose from different open-source connection pool implementations as needed. -- Data access framework: Applications usually use a data access framework such as [MyBatis](https://mybatis.org/mybatis-3/index.html) and [Hibernate](https://hibernate.org/) to further simplify and manage the database access operations. -- Application implementation: The application logic controls when to send what commands to the database. Some applications use [Spring Transaction](https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html) aspects to manage transactions' start and commit logics. - -![Java application components](/media/best-practices/java-practice-1.png) - -From the above diagram, you can see that a Java application might do the following things: - -- Implement the MySQL protocol via the JDBC API to interact with TiDB. -- Get a persistent connection from the connection pool. -- Use a data access framework such as MyBatis to generate and execute SQL statements. -- Use Spring Transaction to automatically start or stop a transaction. - -The rest of this document describes the issues and their solutions when you develop a Java application using the above components. - -## JDBC - -Java applications can be encapsulated with various frameworks. In most of the frameworks, JDBC API is called on the bottommost level to interact with the database server. For JDBC, it is recommended that you focus on the following things: - -- JDBC API usage choice -- API Implementer's parameter configuration - -### JDBC API - -For JDBC API usage, see [JDBC official tutorial](https://docs.oracle.com/javase/tutorial/jdbc/). This section covers the usage of several important APIs. - -#### Use Prepare API - -For OLTP (Online Transactional Processing) scenarios, the SQL statements sent by the program to the database are several types that can be exhausted after removing parameter changes. Therefore, it is recommended to use [Prepared Statements](https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) instead of regular [execution from a text file](https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html#executing_queries) and reuse Prepared Statements to execute directly. This avoids the overhead of repeatedly parsing and generating SQL execution plans in TiDB. - -At present, most upper-level frameworks call the Prepare API for SQL execution. If you use the JDBC API directly for development, pay attention to choosing the Prepare API. - -In addition, with the default implementation of MySQL Connector/J, only client-side statements are preprocessed, and the statements are sent to the server in a text file after `?` is replaced on the client. Therefore, in addition to using the Prepare API, you also need to configure `useServerPrepStmts = true` in JDBC connection parameters before you perform statement preprocessing on the TiDB server. For detailed parameter configuration, see [MySQL JDBC parameters](#mysql-jdbc-parameters). - -#### Use Batch API - -For batch inserts, you can use the [`addBatch`/`executeBatch` API](https://www.tutorialspoint.com/jdbc/jdbc-batch-processing). The `addBatch()` method is used to cache multiple SQL statements first on the client, and then send them to the database server together when calling the `executeBatch` method. - -> **Note:** -> -> In the default MySQL Connector/J implementation, the sending time of the SQL statements that are added to batch with `addBatch()` is delayed to the time when `executeBatch()` is called, but the statements will still be sent one by one during the actual network transfer. Therefore, this method usually does not reduce the amount of communication overhead. -> -> If you want to batch network transfer, you need to configure `rewriteBatchedStatements = true` in the JDBC connection parameters. For the detailed parameter configuration, see [Batch-related parameters](#batch-related-parameters). - -#### Use `StreamingResult` to get the execution result - -In most scenarios, to improve execution efficiency, JDBC obtains query results in advance and save them in client memory by default. But when the query returns a super large result set, the client often wants the database server to reduce the number of records returned at a time, and waits until the client's memory is ready and it requests for the next batch. - -The following two processing methods are usually used in JDBC: - -- The first method: [Set `FetchSize` to `Integer.MIN_VALUE`](https://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html#ResultSet) to ensure that the client does not cache. The client will read the execution result from the network connection through `StreamingResult`. - - When the client uses the streaming read method, it needs to finish reading or close `resultset` before continuing to use the statement to make a query. Otherwise, the error `No statements may be issued when any streaming result sets are open and in use on a given connection. Ensure that you have called .close() on any active streaming result sets before attempting more queries.` is returned. - - To avoid such an error in queries before the client finishes reading or closes `resultset`, you can add the `clobberStreamingResults=true` parameter in the URL. Then, `resultset` is automatically closed but the result set to be read in the previous streaming query is lost. - -- The second method: Use Cursor Fetch by first [setting `FetchSize`](http://makejavafaster.blogspot.com/2015/06/jdbc-fetch-size-performance.html) as a positive integer and then configuring `useCursorFetch = true` in the JDBC URL. - -TiDB supports both methods, but it is recommended that you use the first method that sets `FetchSize` to `Integer.MIN_VALUE`, because it is a simpler implementation and has better execution efficiency. - -For the second method, TiDB first loads all data to the TiDB node, and then returns data to the client according to the `FetchSize`. Therefore, it usually consumes more memory than the first method. If [`tidb_enable_tmp_storage_on_oom`](/system-variables.md#tidb_enable_tmp_storage_on_oom) is set to `ON`, TiDB might temporarily write the result to the hard disk. - -If the [`tidb_enable_lazy_cursor_fetch`](/system-variables.md#tidb_enable_lazy_cursor_fetch-new-in-v830) system variable is set to `ON`, TiDB tries to read part of the data only when the client fetches it, which uses less memory. For more details and limitations, read the [complete descriptions for the `tidb_enable_lazy_cursor_fetch` system variable](/system-variables.md#tidb_enable_lazy_cursor_fetch-new-in-v830). - -### MySQL JDBC parameters - -JDBC usually provides implementation-related configurations in the form of JDBC URL parameters. This section introduces [MySQL Connector/J's parameter configurations](https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html) (If you use MariaDB, see [MariaDB's parameter configurations](https://mariadb.com/kb/en/library/about-mariadb-connector-j/#optional-url-parameters)). Because this document cannot cover all configuration items, it mainly focuses on several parameters that might affect performance. - -#### Prepare-related parameters - -This section introduces parameters related to `Prepare`. - -##### `useServerPrepStmts` - -`useServerPrepStmts` is set to `false` by default, that is, even if you use the Prepare API, the "prepare" operation will be done only on the client. To avoid the parsing overhead of the server, if the same SQL statement uses the Prepare API multiple times, it is recommended to set this configuration to `true`. - -To verify that this setting already takes effect, you can do: - -- Go to TiDB monitoring dashboard and view the request command type through **Query Summary** > **CPS By Instance**. -- If `COM_QUERY` is replaced by `COM_STMT_EXECUTE` or `COM_STMT_PREPARE` in the request, it means this setting already takes effect. - -##### `cachePrepStmts` - -Although `useServerPrepStmts=true` allows the server to execute Prepared Statements, by default, the client closes the Prepared Statements after each execution and does not reuse them. This means that the "prepare" operation is not even as efficient as text file execution. To solve this, it is recommended that after setting `useServerPrepStmts=true`, you should also configure `cachePrepStmts=true`. This allows the client to cache Prepared Statements. - -To verify that this setting already takes effect, you can do: - -- Go to TiDB monitoring dashboard and view the request command type through **Query Summary** > **CPS By Instance**. -- If the number of `COM_STMT_EXECUTE` in the request is far more than the number of `COM_STMT_PREPARE`, it means this setting already takes effect. - -In addition, configuring `useConfigs=maxPerformance` will configure multiple parameters at the same time, including `cachePrepStmts=true`. - -##### `prepStmtCacheSqlLimit` - -After configuring `cachePrepStmts`, also pay attention to the `prepStmtCacheSqlLimit` configuration (the default value is `256`). This configuration controls the maximum length of the Prepared Statements cached on the client. - -The Prepared Statements that exceed this maximum length will not be cached, so they cannot be reused. In this case, you may consider increasing the value of this configuration depending on the actual SQL length of the application. - -You need to check whether this setting is too small if you: - -- Go to TiDB monitoring dashboard and view the request command type through **Query Summary** > **CPS By Instance**. -- And find that `cachePrepStmts=true` has been configured, but `COM_STMT_PREPARE` is still mostly equal to `COM_STMT_EXECUTE` and `COM_STMT_CLOSE` exists. - -##### `prepStmtCacheSize` - -`prepStmtCacheSize` controls the number of cached Prepared Statements (the default value is `25`). If your application requires "preparing" many types of SQL statements and wants to reuse Prepared Statements, you can increase this value. - -To verify that this setting already takes effect, you can do: - -- Go to TiDB monitoring dashboard and view the request command type through **Query Summary** > **CPS By Instance**. -- If the number of `COM_STMT_EXECUTE` in the request is far more than the number of `COM_STMT_PREPARE`, it means this setting already takes effect. - -#### Batch-related parameters - -While processing batch writes, it is recommended to configure `rewriteBatchedStatements=true`. After using `addBatch()` or `executeBatch()`, JDBC still sends SQL one by one by default, for example: - -```java -pstmt = prepare("insert into t (a) values(?)"); -pstmt.setInt(1, 10); -pstmt.addBatch(); -pstmt.setInt(1, 11); -pstmt.addBatch(); -pstmt.setInt(1, 12); -pstmt.executeBatch(); -``` - -Although `Batch` methods are used, the SQL statements sent to TiDB are still individual `INSERT` statements: - -{{< copyable "sql" >}} - -```sql -insert into t(a) values(10); -insert into t(a) values(11); -insert into t(a) values(12); -``` - -But if you set `rewriteBatchedStatements=true`, the SQL statements sent to TiDB will be a single `INSERT` statement: - -{{< copyable "sql" >}} - -```sql -insert into t(a) values(10),(11),(12); -``` - -Note that the rewrite of the `INSERT` statements is to concatenate the values after multiple "values" keywords into a whole SQL statement. If the `INSERT` statements have other differences, they cannot be rewritten, for example: - -{{< copyable "sql" >}} - -```sql -insert into t (a) values (10) on duplicate key update a = 10; -insert into t (a) values (11) on duplicate key update a = 11; -insert into t (a) values (12) on duplicate key update a = 12; -``` - -The above `INSERT` statements cannot be rewritten into one statement. But if you change the three statements into the following ones: - -{{< copyable "sql" >}} - -```sql -insert into t (a) values (10) on duplicate key update a = values(a); -insert into t (a) values (11) on duplicate key update a = values(a); -insert into t (a) values (12) on duplicate key update a = values(a); -``` - -Then they meet the rewrite requirement. The above `INSERT` statements will be rewritten into the following one statement: - -{{< copyable "sql" >}} - -```sql -insert into t (a) values (10), (11), (12) on duplicate key update a = values(a); -``` - -If there are three or more updates during the batch update, the SQL statements will be rewritten and sent as multiple queries. This effectively reduces the client-to-server request overhead, but the side effect is that a larger SQL statement is generated. For example: - -{{< copyable "sql" >}} - -```sql -update t set a = 10 where id = 1; update t set a = 11 where id = 2; update t set a = 12 where id = 3; -``` - -In addition, because of a [client bug](https://bugs.mysql.com/bug.php?id=96623), if you want to configure `rewriteBatchedStatements=true` and `useServerPrepStmts=true` during batch update, it is recommended that you also configure the `allowMultiQueries=true` parameter to avoid this bug. - -#### Integrate parameters - -Through monitoring, you might notice that although the application only performs `INSERT` operations to the TiDB cluster, there are a lot of redundant `SELECT` statements. Usually this happens because JDBC sends some SQL statements to query the settings, for example, `select @@session.transaction_read_only`. These SQL statements are useless for TiDB, so it is recommended that you configure `useConfigs=maxPerformance` to avoid extra overhead. - -`useConfigs=maxPerformance` includes a group of configurations. To get the detailed configurations in MySQL Connector/J 8.0 and those in MySQL Connector/J 5.1, see [mysql-connector-j 8.0](https://github.com/mysql/mysql-connector-j/blob/release/8.0/src/main/resources/com/mysql/cj/configurations/maxPerformance.properties) and [mysql-connector-j 5.1](https://github.com/mysql/mysql-connector-j/blob/release/5.1/src/com/mysql/jdbc/configs/maxPerformance.properties) respectively. - -After it is configured, you can check the monitoring to see a decreased number of `SELECT` statements. - -> **Note:** -> -> Enabling `useConfigs=maxPerformance` requires MySQL Connector/J version 8.0.33 or later. For more details, see [MySQL JDBC Bug](/develop/dev-guide-third-party-tools-compatibility.md#mysql-jdbc-bugs). - -#### Timeout-related parameters - -TiDB provides two MySQL-compatible parameters that controls the timeout: `wait_timeout` and `max_execution_time`. These two parameters respectively control the connection idle timeout with the Java application and the timeout of the SQL execution in the connection; that is to say, these parameters control the longest idle time and the longest busy time for the connection between TiDB and the Java application. The default value of both parameters is `0`, which by default allows the connection to be infinitely idle and infinitely busy (an infinite duration for one SQL statement to execute). - -However, in an actual production environment, idle connections and SQL statements with excessively long execution time negatively affect databases and applications. To avoid idle connections and SQL statements that are executed for too long, you can configure these two parameters in your application's connection string. For example, set `sessionVariables=wait_timeout=3600` (1 hour) and `sessionVariables=max_execution_time=300000` (5 minutes). - -#### Typical JDBC connection string parameters - -Combining the preceding parameter values, the JDBC connection string configuration is as follows: - -``` -jdbc:mysql://:/?characterEncoding=UTF-8&useSSL=false&useServerPrepStmts=true&cachePrepStmts=true&prepStmtCacheSqlLimit=10000&prepStmtCacheSize=1000&useConfigs=maxPerformance&rewriteBatchedStatements=true -``` - -> **Note:** -> -> If you are connecting over a public network, you need to set `useSSL=true` and [enable TLS between TiDB clients and servers](/enable-tls-between-clients-and-servers.md). - -## Connection pool - -Building TiDB (MySQL) connections is relatively expensive (for OLTP scenarios at least), because in addition to building a TCP connection, connection authentication is also required. Therefore, the client usually saves the TiDB (MySQL) connections to the connection pool for reuse. - -TiDB supports the following Java connection pools: - -- [HikariCP](https://github.com/brettwooldridge/HikariCP) -- [tomcat-jdbc](https://tomcat.apache.org/tomcat-10.1-doc/jdbc-pool) -- [druid](https://github.com/alibaba/druid) -- [c3p0](https://www.mchange.com/projects/c3p0/) -- [dbcp](https://commons.apache.org/proper/commons-dbcp/) - -In practice, some connection pools might persistently use specific active sessions. Although the total number of connections appears evenly distributed across TiDB compute nodes, uneven distribution of active connections can lead to actual load imbalance. In distributed scenarios, it is recommended to use HikariCP, which manages connection lifecycles effectively and helps prevent active connections from being fixed on certain nodes, achieving balanced load distribution. - -### Typical connection pool configuration - -The following is an example configuration for HikariCP: - -```yaml -hikari: - maximumPoolSize: 20 - poolName: hikariCP - connectionTimeout: 30000 - maxLifetime: 1200000 - keepaliveTime: 120000 -``` - -The parameter explanations are as follows. For more details, refer to the [official HikariCP documentation](https://github.com/brettwooldridge/HikariCP/blob/dev/README.md). - -- `maximumPoolSize`: the maximum number of connections in the pool. The default value is `10`. In containerized environments, it is recommended to set this to 4–10 times the number of CPU cores available to the Java application. Setting this value too high can lead to resource wastage, while setting it too low can slow down connection acquisition. See [About Pool Sizing](https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing) for more details. -- `minimumIdle`: HikariCP recommends not setting this parameter. The default value is equal to the value of `maximumPoolSize`, which disables connection pool scaling. This ensures that connections are readily available during traffic spikes and avoids delays caused by connection creation. -- `connectionTimeout`: the maximum time (in milliseconds) that an application waits to acquire a connection from the pool. The default value is `30000` milliseconds (30 seconds). If no available connection is obtained within this time, a `SQLException` exception occurs. -- `maxLifetime`: the maximum lifetime (in milliseconds) of a connection in the pool. The default value is `1800000` milliseconds (30 minutes). Connections in use are not affected. After the connection is closed, it will be removed according to this setting. Setting this value too low can cause frequent reconnections. If you are using [`graceful-wait-before-shutdown`](/tidb-configuration-file.md#graceful-wait-before-shutdown-new-in-v50), ensure this value is less than the wait time. -- `keepaliveTime`: the interval (in milliseconds) between keepalive operations on connections in the pool. This setting helps prevent disconnections caused by database or network idle timeouts. The default value is `120000` milliseconds (2 minutes). The pool prefers using the JDBC4 `isValid()` method to keep idle connections alive. - -### Probe configuration - -The connection pool maintains persistent connections from clients to TiDB as follows: - -- Before v5.4, TiDB does not proactively close client connections by default (unless an error is reported). -- Starting from v5.4, TiDB automatically closes client connections after `28800` seconds (this is, `8` hours) of inactivity by default. You can control this timeout setting using the TiDB and MySQL compatible `wait_timeout` variable. For more information, see [JDBC Query Timeout](/develop/dev-guide-timeouts-in-tidb.md#jdbc-query-timeout). - -Moreover, there might be network proxies such as [LVS](https://en.wikipedia.org/wiki/Linux_Virtual_Server) or [HAProxy](https://en.wikipedia.org/wiki/HAProxy) between clients and TiDB. These proxies typically proactively clean up connections after a specific idle period (determined by the proxy's idle configuration). In addition to monitoring the proxy's idle configuration, connection pools also need to maintain or probe connections for keep-alive. - -If you often see the following error in your Java application: - -``` -The last packet sent successfully to the server was 3600000 milliseconds ago. The driver has not received any packets from the server. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure -``` - -If `n` in `n milliseconds ago` is `0` or a very small value, it is usually because the executed SQL operation causes TiDB to exit abnormally. To find the cause, it is recommended to check the TiDB stderr log. - -If `n` is a very large value (such as `3600000` in the above example), it is likely that this connection was idle for a long time and then closed by the intermediate proxy. The usual solution is to increase the value of the proxy's idle configuration and allow the connection pool to: - -- Check whether the connection is available before using the connection every time -- Regularly check whether the connection is available using a separate thread. -- Send a test query regularly to keep alive connections - -Different connection pool implementations might support one or more of the above methods. You can check your connection pool documentation to find the corresponding configuration. - -## Data access framework - -Applications often use some kind of data access framework to simplify database access. - -### MyBatis - -[MyBatis](http://www.mybatis.org/mybatis-3/) is a popular Java data access framework. It is mainly used to manage SQL queries and complete the mapping between result sets and Java objects. MyBatis is highly compatible with TiDB. MyBatis rarely has problems based on its historical issues. - -Here this document mainly focuses on the following configurations. - -#### Mapper parameters - -MyBatis Mapper supports two parameters: - -- `select 1 from t where id = #{param1}` will be converted to `select 1 from t where id =?` as a Prepared Statement and be "prepared", and the actual parameter will be used for reuse. You can get the best performance when using this parameter with the previously mentioned Prepare connection parameters. -- `select 1 from t where id = ${param2}` will be replaced with `select 1 from t where id = 1` as a text file and be executed. If this statement is replaced with different parameters and is executed, MyBatis will send different requests for "preparing" the statements to TiDB. This might cause TiDB to cache a large number of Prepared Statements, and executing SQL operations this way has injection security risks. - -#### Dynamic SQL Batch - -[Dynamic SQL - foreach](http://www.mybatis.org/mybatis-3/dynamic-sql.html#foreach) - -To support the automatic rewriting of multiple `INSERT` statements into the form of `insert ... values(...), (...), ...`, in addition to configuring `rewriteBatchedStatements=true` in JDBC as mentioned before, MyBatis can also use dynamic SQL to semi-automatically generate batch inserts. Take the following mapper as an example: - -```xml - - insert into test - (id, v1, v2) - values - - ( - #{item.id}, #{item.v1}, #{item.v2} - ) - - on duplicate key update v2 = v1 + values(v1) - -``` - -This mapper generates an `insert on duplicate key update` statement. The number of `(?,?,?)` following "values" is determined by the number of passed lists. Its final effect is similar to using `rewriteBatchStatements=true`, which also effectively reduces communication overhead between the client and TiDB. - -As mentioned before, you also need to note that the Prepared Statements will not be cached after their maximum length exceeds the value of `prepStmtCacheSqlLimit`. - -#### Streaming result - -[A previous section](#use-streamingresult-to-get-the-execution-result) introduces how to stream read execution results in JDBC. In addition to the corresponding configurations of JDBC, if you want to read a super large result set in MyBatis, you also need to note that: - -- You can set `fetchSize` for a single SQL statement in the mapper configuration (see the previous code block). Its effect is equivalent to calling `setFetchSize` in JDBC. -- You can use the query interface with `ResultHandler` to avoid getting the entire result set at once. -- You can use the `Cursor` class for stream reading. - -If you configure mappings using XML, you can stream read results by configuring `fetchSize="-2147483648"`(`Integer.MIN_VALUE`) in the mapping's ` - select * from post; - -``` - -If you configure mappings using code, you can add the `@Options(fetchSize = Integer.MIN_VALUE)` annotation and keep the type of results as `Cursor` so that the SQL results can be read in streaming. - -```java -@Select("select * from post") -@Options(fetchSize = Integer.MIN_VALUE) -Cursor queryAllPost(); -``` - -### `ExecutorType` - -You can choose `ExecutorType` during `openSession`. MyBatis supports three types of executors: - -- Simple: The Prepared Statements are called to JDBC for each execution (if the JDBC configuration item `cachePrepStmts` is enabled, repeated Prepared Statements will be reused) -- Reuse: The Prepared Statements are cached in `executor`, so that you can reduce duplicate calls for Prepared Statements without using the JDBC `cachePrepStmts` -- Batch: Each update operation (`INSERT`/`DELETE`/`UPDATE`) will first be added to the batch, and will be executed until the transaction commits or a `SELECT` query is performed. If `rewriteBatchStatements` is enabled in the JDBC layer, it will try to rewrite the statements. If not, the statements will be sent one by one. - -Usually, the default value of `ExecutorType` is `Simple`. You need to change `ExecutorType` when calling `openSession`. If it is the batch execution, you might find that in a transaction the `UPDATE` or `INSERT` statements are executed pretty fast, but it is slower when reading data or committing the transaction. This is actually normal, so you need to note this when troubleshooting slow SQL queries. - -## Spring Transaction - -In the real world, applications might use [Spring Transaction](https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html) and AOP aspects to start and stop transactions. - -By adding the `@Transactional` annotation to the method definition, AOP starts the transaction before the method is called, and commits the transaction before the method returns the result. If your application has a similar need, you can find `@Transactional` in code to determine when the transaction is started and closed. - -Pay attention to a special case of embedding. If it occurs, Spring will behave differently based on the [Propagation](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Propagation.html) configuration. - -## Misc - -This section introduces some useful tools for Java to help you troubleshoot issues. - -### Troubleshooting tools - -Using the powerful troubleshooting tools of JVM is recommended when an issue occurs in your Java application and you do not know the application logic. Here are a few common tools: - -#### jstack - -[jstack](https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstack.html) is similar to pprof/goroutine in Go, which can easily troubleshoot the process stuck issue. - -By executing `jstack pid`, you can output the IDs and stack information of all threads in the target process. By default, only the Java stack is output. If you want to output the C++ stack in the JVM at the same time, add the `-m` option. - -By using jstack multiple times, you can easily locate the stuck issue (for example, a slow query from application's view due to using Batch ExecutorType in Mybatis) or the application deadlock issue (for example, the application does not send any SQL statement because it is preempting a lock before sending it). - -In addition, `top -p $ PID -H` or Java swiss knife are common methods to view the thread ID. Also, to locate the issue of "a thread occupies a lot of CPU resources and I don't know what it is executing", do the following steps: - -- Use `printf "%x\n" pid` to convert the thread ID to hexadecimal. -- Go to the jstack output to find the stack information of the corresponding thread. - -#### jmap & mat - -Unlike pprof/heap in Go, [jmap](https://docs.oracle.com/javase/7/docs/technotes/tools/share/jmap.html) dumps the memory snapshot of the entire process (in Go, it is the sampling of the distributor), and then the snapshot can be analyzed by another tool [mat](https://www.eclipse.org/mat/). - -Through mat, you can see the associated information and attributes of all objects in the process, and you can also observe the running status of the thread. For example, you can use mat to find out how many MySQL connection objects exist in the current application, and what is the address and status information of each connection object. - -Note that mat only handles reachable objects by default. If you want to troubleshoot young GC issues, you can adjust mat configuration to view unreachable objects. In addition, for investigating the memory allocation of young GC issues (or a large number of short-lived objects), using Java Flight Recorder is more convenient. - -#### trace - -Online applications usually do not support modifying the code, but it is often desired that dynamic instrumentation is performed in Java to locate issues. Therefore, using btrace or arthas trace is a good option. They can dynamically insert trace code without restarting the application process. - -#### Flame graph - -Obtaining flame graphs in Java applications is tedious. For details, see [Java Flame Graphs Introduction: Fire For Everyone!](http://psy-lob-saw.blogspot.com/2017/02/flamegraphs-intro-fire-for-everyone.html). - -## Conclusion - -Based on commonly used Java components that interact with databases, this document describes the common problems and solutions for developing Java applications with TiDB. TiDB is highly compatible with the MySQL protocol, so most of the best practices for MySQL-based Java applications also apply to TiDB. - -## Need help? - -Ask the community on [Discord](https://discord.gg/DQZ2dy3cuc?utm_source=doc) or [Slack](https://slack.tidb.io/invite?team=tidb-community&channel=everyone&ref=pingcap-docs), or [submit a support ticket](/support.md). \ No newline at end of file diff --git a/ddl-introduction.md b/ddl-introduction.md deleted file mode 100644 index d489e70f13898..0000000000000 --- a/ddl-introduction.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: TiDB 中 DDL 执行的最佳实践 -summary: 了解 TiDB 中 DDL 语句的实现方式、在线变更流程以及最佳实践。 ---- - -# TiDB 中 DDL 执行的最佳实践 - -本文档概述了 TiDB 中与 DDL 语句相关的执行原理和最佳实践。原理包括 DDL Owner 模块和在线 DDL 变更流程。 - -## DDL 执行原理 - -TiDB 采用在线异步方式执行 DDL 语句。这意味着在执行 DDL 语句时,其他会话中的 DML 语句不会被阻塞。换句话说,你可以在应用程序运行时,使用在线异步的 DDL 语句修改数据库对象的定义。 - -### DDL 语句类型 - -TiDB 支持在线 DDL,这意味着在数据库中执行 DDL 语句时,采用特定的方法确保该操作不会阻塞用户应用。你可以在 DDL 执行期间提交数据修改,数据库保证数据的一致性和正确性。 - -相比之下,离线 DDL 会锁定数据库对象,阻塞用户的修改,直到 DDL 操作完成。TiDB 不支持离线 DDL。 - -根据是否操作目标 DDL 对象中的数据,DDL 语句可以分为以下类型: - -- **Logical DDL 语句**:逻辑 DDL 语句通常只修改数据库对象的元数据,不处理存储在对象中的数据,例如更改表名或列名。 - - 在 TiDB 中,逻辑 DDL 也称为“通用 DDL”。这些语句的执行时间通常较短,常常只需几十毫秒或几秒即可完成。因此,它们消耗的系统资源较少,不会影响应用的工作负载。 - -- **Physical DDL 语句**:物理 DDL 语句不仅修改被变更对象的元数据,还会修改存储在对象中的用户数据。例如,当 TiDB 为一张表创建索引时,不仅会改变表的定义,还会进行全表扫描以构建新添加的索引。 - - 在 TiDB 中,物理 DDL 也称为“reorg DDL”,代表重组。目前,物理 DDL 仅包括 `ADD INDEX` 和有损列类型变更(如从 `INT` 类型变更为 `CHAR` 类型)。这些操作的执行时间较长,受表中数据量、机器配置和应用负载的影响。 - - 执行物理 DDL 可能对应用的工作负载产生影响,原因有二:一方面,它会消耗 TiKV 的 CPU 和 I/O 资源,用于读取和写入数据;另一方面,**作为 DDL Owner 的 TiDB 节点** 或 **由 TiDB 分布式执行框架(DXF)调度执行 `ADD INDEX` 任务的 TiDB 节点**,会消耗 CPU 资源进行相应的计算。 - - > **Note:** - > - > 执行物理 DDL 任务通常对用户应用的影响最大。因此,为了最小化影响,关键在于在执行过程中优化物理 DDL 语句的设计。这有助于减少对用户应用的影响。 - -### TiDB DDL 模块 - -TiDB 的 DDL 模块引入了 DDL Owner(或 Owner)角色,作为在 TiDB 集群中执行所有 DDL 语句的代理。在当前实现中,整个集群中最多只有一个 TiDB 节点可以被选举为 Owner。一旦某个 TiDB 节点当选为 Owner,该节点启动的工作线程就可以处理集群中的 DDL 任务。 - -TiDB 使用 etcd 的选举机制,从多个 TiDB 节点中选举出一个节点作为 Owner。默认情况下,每个 TiDB 节点都可能被选举为 Owner(你可以配置 `run-ddl` 来管理节点参与选举)。当选的 Owner 节点有一个任期(term),它会通过续期主动维护该任期。当 Owner 节点宕机时,其他节点可以通过 etcd 选举出新的 Owner,继续在集群中执行 DDL 任务。 - -一个简单的 DDL Owner 示意图如下: - -![DDL Owner](/media/ddl-owner.png) - -你可以使用 `ADMIN SHOW DDL` 语句查看当前的 DDL Owner: - -```sql -ADMIN SHOW DDL; -``` - -```sql -+------------+--------------------------------------+---------------+--------------+--------------------------------------+-------+ -| SCHEMA_VER | OWNER_ID | OWNER_ADDRESS | RUNNING_JOBS | SELF_ID | QUERY | -+------------+--------------------------------------+---------------+--------------+--------------------------------------+-------+ -| 26 | 2d1982af-fa63-43ad-a3d5-73710683cc63 | 0.0.0.0:4000 | | 2d1982af-fa63-43ad-a3d5-73710683cc63 | | -+------------+--------------------------------------+---------------+--------------+--------------------------------------+-------+ -``` - -### TiDB 中在线 DDL 异步变更的工作原理 - -从设计之初,TiDB 的 DDL 模块就采用了在线异步变更模式,允许你在不影响应用的情况下修改。 - -DDL 变更涉及状态的转换,通常从“变更前”状态到“变更后”状态。采用在线 DDL 时,这一转换通过引入多个相互兼容的小版本状态实现。在执行 DDL 语句期间,TiDB 集群中的节点可以拥有不同的小版本变更,只要相邻的小版本之间的差异不超过两个版本。这是因为相邻的小版本可以相互兼容。 - -这样,通过多个小版本的演进,确保元数据可以在多个 TiDB 节点间正确同步,有助于在变更过程中保持涉及数据变更的用户事务的正确性和一致性。 - -以 `ADD INDEX` 为例,整个状态变更过程如下: - -``` -absent -> delete only -> write only -> write reorg -> public -``` - -对于用户而言,直到进入 `public` 状态之前,新创建的索引都是不可用的。 - - -
- -在 TiDB v6.2.0 之前,由于 Owner 一次只能执行一种类型(逻辑或物理)的 DDL 任务,限制较为严格,影响用户体验。 - -如果 DDL 任务之间没有依赖关系,并行执行不会影响数据的正确性和一致性。例如,用户 A 给 `T1` 表添加索引,而用户 B 删除 `T2` 表中的列,这两个 DDL 语句可以并行执行。 - -为了改善 DDL 执行的用户体验,从 v6.2.0 开始,TiDB 允许 Owner 根据 DDL 任务的相关性进行判断,逻辑如下: - -+ 对同一张表的 DDL 语句相互阻塞。 -+ `DROP DATABASE` 和影响数据库中所有对象的 DDL 语句相互阻塞。 -+ 在不同表上添加索引和列类型变更可以并发执行。 -+ 从 v8.2.0 开始,不同表的 [逻辑 DDL 语句](/ddl-introduction.md#types-of-ddl-statements) 可以并行执行。 -+ 在其他情况下,DDL 可以根据可用性等级进行并发执行。 - -具体而言,TiDB 6.2.0 在以下方面增强了 DDL 执行框架: - -+ DDL Owner 可以根据上述逻辑并行执行 DDL 任务。 -+ 解决 DDL 任务队列中的先进先出问题。DDL Owner 不再只选择队列中的第一个任务,而是选择当前可以执行的任务。 -+ 增加处理物理 DDL 语句的工作线程数,支持多个物理 DDL 并行执行。 - - 由于 TiDB 中所有 DDL 任务都采用在线变更方式实现,Owner 可以根据新 DDL 任务的相关性进行调度,从而实现与传统数据库相同的 DDL 并发水平。 - -并发 DDL 框架提升了 TiDB 中 DDL 语句的执行能力,使其更好地适应商业数据库的使用场景。 - -
-
- -在 v6.2.0 之前,TiDB SQL 层处理异步模式变更的流程如下: - -1. MySQL 客户端向 TiDB 服务器发送 DDL 请求。 - -2. TiDB 服务器收到请求后,在 MySQL 协议层解析和优化请求,然后将其发送到 TiDB SQL 层执行。 - - 一旦 TiDB 的 SQL 层收到 DDL 请求,它会启动 `start job` 模块,将请求封装成特定的 DDL 任务(即 DDL Job),然后根据语句类型将其存入对应的 DDL 任务队列(在 KV 层)。相关工作线程会被通知处理该任务。 - -3. 当工作线程收到处理任务的通知时,会判断自己是否为 DDL Owner。如果是,则直接处理任务;否则不进行任何处理。 - - 如果 TiDB 服务器不是 Owner 角色,则必须由其他节点担任 Owner。Owner 角色的工作线程会定期检查是否有可执行的任务。如果发现有,则会处理该任务。 - -4. 工作线程处理完 Job 后,会将任务从 KV 层的任务队列中移除,并放入 `job history queue`。封装 Job 的 `start job` 模块会定期检查 `job history queue` 中任务的 ID,确认是否已处理完毕。如果已完成,整个 DDL 操作也就结束了。 - -5. TiDB 服务器将 DDL 处理结果返回给 MySQL 客户端。 - -在 v6.2.0 之前,TiDB 的 DDL 执行框架存在以下限制: - -- TiKV 集群只有两个队列:`general job queue` 和 `add index job queue`,分别处理逻辑 DDL 和物理 DDL。 -- DDL Owner 始终以先进先出方式处理 DDL 任务。 -- DDL Owner 一次只能执行一个相同类型(逻辑或物理)的 DDL 任务,限制较为严格,影响用户体验。 - -这些限制可能导致一些“非预期”的 DDL 阻塞行为。更多详情请参见 [SQL FAQ - DDL Execution](https://docs.pingcap.com/tidb/stable/sql-faq#ddl-execution)。 - -
-
- -## 最佳实践 - -### 通过系统变量平衡物理 DDL 执行速度与应用负载影响 - -在执行物理 DDL 语句(包括添加索引或列类型变更)时,可以调整以下系统变量的值,以平衡 DDL 执行速度和对应用负载的影响: - -- [`tidb_ddl_reorg_worker_cnt`](/system-variables.md#tidb_ddl_reorg_worker_cnt):设置 DDL 操作的重组织工作线程数,控制回填的并发度。 - -- [`tidb_ddl_reorg_batch_size`](/system-variables.md#tidb_ddl_reorg_batch_size):设置 `re-organize` 阶段的批量大小,控制回填的数据量。 - - 推荐值: - - - 如果没有其他负载,可以增大 `tidb_ddl_reorg_worker_cnt` 和 `tidb_ddl_reorg_batch_size` 的值,加快 `ADD INDEX` 的速度。例如,将两个变量的值分别设置为 `20` 和 `2048`。 - - 如果存在其他负载,可以减小这两个变量的值,以最小化对其他应用的影响。例如,将它们的值设置为 `4` 和 `256`。 - -> **Tip:** -> -> - 以上两个变量可以在 DDL 任务执行过程中动态调整,并在下一批事务中生效。 -> - 根据操作类型和应用负载压力选择合适的时间执行 DDL 操作。例如,建议在应用负载较低时执行 `ADD INDEX`。 -> - 由于添加索引的时间较长,TiDB 会在命令发出后在后台执行任务。如果 TiDB 服务器宕机,执行不会受到影响。 - -### 通过并发发送 DDL 请求快速创建大量表 - -创建一张表大约需要 50 毫秒。实际耗时可能更长,原因在于框架限制。 - -为了更快地创建表,建议同时发送多个 DDL 请求,以实现最快的创建速度。如果串行发送 DDL 请求且不在 Owner 节点,表创建速度会非常慢。 - -### 在单个 `ALTER` 语句中进行多项变更 - -从 v6.2.0 开始,TiDB 支持在单个 `ALTER` 语句中修改多个表结构对象(如列和索引),同时保证整个语句的原子性。因此,建议在单个 `ALTER` 语句中进行多项变更。 - -### 检查读写性能 - -当 TiDB 添加索引时,回填数据阶段会对集群造成读写压力。发出 `ADD INDEX` 命令并开始 `write reorg` 阶段后,建议通过 Grafana 仪表盘监控 TiDB 和 TiKV 的读写性能指标,以及应用响应时间,以判断 `ADD INDEX` 操作是否影响集群。 - -## 与 DDL 相关的命令 - -- `ADMIN SHOW DDL`:用于查看 TiDB DDL 操作的状态,包括当前的 schema 版本号、DDL Owner 的 ID 和地址、正在执行的 DDL 任务和 SQL,以及当前 TiDB 实例的 DDL ID。详情请参见 [`ADMIN SHOW DDL`](/sql-statements/sql-statement-admin-show-ddl.md#admin-show-ddl)。 - -- `ADMIN SHOW DDL JOBS`:用于查看集群中正在运行的 DDL 任务的详细状态。详情请参见 [`ADMIN SHOW DDL JOBS`](/sql-statements/sql-statement-admin-show-ddl.md#admin-show-ddl-jobs)。 - -- `ADMIN SHOW DDL JOB QUERIES job_id [, job_id]`:用于查看对应 `job_id` 的 DDL 任务的原始 SQL 语句。详情请参见 [`ADMIN SHOW DDL JOB QUERIES`](/sql-statements/sql-statement-admin-show-ddl.md#admin-show-ddl-job-queries)。 - -- `ADMIN CANCEL DDL JOBS job_id [, job_id]`:用于取消已提交但未完成的 DDL 任务。取消完成后,执行 DDL 任务的 SQL 语句会返回 `ERROR 8214 (HY000): Cancelled DDL job` 错误。 - - 如果取消已完成的 DDL 任务,可以在 `RESULT` 列看到 `DDL Job:90 not found` 错误,表示该任务已从 DDL 等待队列中移除。 - -- `ADMIN PAUSE DDL JOBS job_id [, job_id]`:用于暂停正在执行的 DDL 任务。执行后,执行 DDL 任务的 SQL 语句显示为正在执行,而后台任务已暂停。详情请参见 [`ADMIN PAUSE DDL JOBS`](/sql-statements/sql-statement-admin-pause-ddl.md)。 - - 只能暂停进行中或在队列中的 DDL 任务,否则在 `RESULT` 列会显示 `Job 3 can't be paused now` 错误。 - -- `ADMIN RESUME DDL JOBS job_id [, job_id]`:用于恢复已暂停的 DDL 任务。执行后,执行 DDL 任务的 SQL 语句显示为正在执行,后台任务恢复。详情请参见 [`ADMIN RESUME DDL JOBS`](/sql-statements/sql-statement-admin-resume-ddl.md)。 - - 只能恢复已暂停的 DDL 任务,否则在 `RESULT` 列会显示 `Job 3 can't be resumed` 错误。 - -## 与 DDL 相关的表 - -- [`information_schema.DDL_JOBS`](/information-schema/information-schema-ddl-jobs.md):当前正在运行和已完成的 DDL 任务信息。 -- [`mysql.tidb_mdl_view`](/mysql-schema/mysql-schema-tidb-mdl-view.md):关于 [metadata lock](/metadata-lock.md) 视图的信息,可帮助识别阻塞 DDL 进展的查询。 - -## 常见问题 - -关于 DDL 执行的常见问题,参见 [SQL FAQ - DDL execution](https://docs.pingcap.com/tidb/stable/sql-faq)。 \ No newline at end of file diff --git a/develop/dev-guide-overview.md b/develop/dev-guide-overview.md deleted file mode 100644 index 09f6d048f9d11..0000000000000 --- a/develop/dev-guide-overview.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: 开发者指南概览 -summary: 介绍 TiDB Cloud 和 TiDB 自托管的开发者指南总览。 ---- - -# 开发者指南概览 - - - - - - - -## 按语言和框架的指南 - -按照示例代码,使用你所用的语言构建应用。 - - - - -在边缘环境中通过 HTTPS 连接到 TiDB Cloud。 - - - - -将 Next.js 与 mysql2 连接到 TiDB Cloud。 - - - - -使用 Prisma ORM 连接到 TiDB Cloud。 - - - - -使用 TypeORM 连接到 TiDB Cloud。 - - - - -使用 Sequelize ORM 连接到 TiDB Cloud。 - - - - -使用 Node.js 的 mysql.js 模块连接到 TiDB Cloud。 - - - - -使用 Node.js 的 node-mysql2 模块连接到 TiDB Cloud。 - - - - -将 AWS Lambda 函数通过 mysql2 连接到 TiDB Cloud。 - - - - - - - -将 Django 应用通过 django-tidb 连接到 TiDB Cloud。 - - - - -使用官方 MySQL 包连接到 TiDB Cloud。 - - - - -使用 PyMySQL 包连接到 TiDB Cloud。 - - - - -使用 mysqlclient 包连接到 TiDB Cloud。 - - - - -使用 SQLAlchemy ORM 连接到 TiDB Cloud。 - - - - -使用 Peewee ORM 连接到 TiDB Cloud。 - - - - - - - -使用 JDBC(MySQL Connector/J)连接到 TiDB Cloud。 - - - - -使用 MyBatis ORM 连接到 TiDB Cloud。 - - - - -使用 Hibernate ORM 连接到 TiDB Cloud。 - - - - -将基于 Spring 的应用通过 Spring Data JPA 连接到 TiDB Cloud。 - - - - - - - -使用 Go 的 MySQL 驱动连接到 TiDB Cloud。 - - - - -使用 GORM 连接到 TiDB Cloud。 - - - - - - - -将 Ruby on Rails 应用通过 Active Record ORM 连接到 TiDB Cloud。 - - - - -使用 mysql2 驱动连接到 TiDB Cloud。 - - - - -除了这些指南外,PingCAP 还与社区合作支持 [第三方 MySQL 驱动、ORM 和工具](/develop/dev-guide-third-party-support.md)。 - -## 使用 MySQL 客户端软件 - -由于 TiDB 兼容 MySQL,你可以使用许多熟悉的客户端工具连接到 TiDB Cloud 并管理你的数据库。或者,你也可以使用我们的 命令行工具 来连接和管理你的数据库。 - - - - -使用 MySQL Workbench 连接并管理 TiDB Cloud 数据库。 - - - - -在 VS Code 中通过 SQLTools 扩展连接并管理 TiDB Cloud 数据库。 - - - - -使用 DBeaver 连接并管理 TiDB Cloud 数据库。 - - - - -使用 JetBrains 的 DataGrip 连接并管理 TiDB Cloud 数据库。 - - - - -## 其他资源 - -了解使用 TiDB Cloud 进行开发的其他主题。 - -- 使用 TiDB Cloud CLI 进行开发、管理和部署你的应用。 -- 探索与 TiDB Cloud 的流行 服务集成。 -- 参考 [TiDB 数据库开发参考](/develop/dev-guide-schema-design-overview.md),设计、交互、优化和排查你的数据和模式。 -- 参加免费在线课程 [TiDB 入门](https://eng.edu.pingcap.com/catalog/info/id:203/?utm_source=docs-dev-guide)。 - - - - - -本指南面向应用开发者,但如果你对 TiDB 的内部工作机制感兴趣或希望参与 TiDB 的开发,可以阅读 [TiDB 内核开发指南](https://pingcap.github.io/tidb-dev-guide/) 以获取更多关于 TiDB 的信息。 - -本教程展示了如何快速使用 TiDB 构建应用,TiDB 的潜在用例以及如何处理常见问题。 - -在阅读本页面之前,建议你先阅读 [TiDB 自托管快速入门](https://docs.pingcap.com/tidb/v8.5/quick-start-with-tidb/)。 - -## TiDB 基础知识 - -在开始使用 TiDB 之前,你需要了解一些 TiDB 工作机制的重要内容: - -- 阅读 [TiDB 事务概述](/transaction-overview.md),了解 TiDB 中事务的工作原理,或者查看 [应用开发者的事务笔记](/develop/dev-guide-transaction-overview.md),学习应用开发所需的事务知识。 -- 了解 [应用与 TiDB 的交互方式](#the-way-applications-interact-with-tidb)。 -- 若要学习构建分布式数据库 TiDB 和 TiDB Cloud 的核心组件和概念,可以参考免费在线课程 [TiDB 入门](https://eng.edu.pingcap.com/catalog/info/id:203/?utm_source=docs-dev-guide)。 - -## TiDB 事务机制 - -TiDB 支持分布式事务,并提供 [乐观事务](/optimistic-transaction.md) 和 [悲观事务](/pessimistic-transaction.md) 模式。当前版本的 TiDB 默认为 **悲观事务** 模式,这允许你像使用传统的单体数据库(例如 MySQL)一样进行事务操作。 - -你可以使用 [`BEGIN`](/sql-statements/sql-statement-begin.md) 开始事务,明确指定使用 **悲观事务** 通过 `BEGIN PESSIMISTIC`,或明确指定使用 **乐观事务** 通过 `BEGIN OPTIMISTIC`。之后,可以选择提交([`COMMIT`](/sql-statements/sql-statement-commit.md))或回滚([`ROLLBACK`](/sql-statements/sql-statement-rollback.md))事务。 - -TiDB 保证从 `BEGIN` 开始到 `COMMIT` 或 `ROLLBACK` 结束之间的所有语句具有原子性,即在此期间执行的所有语句要么全部成功,要么全部失败。这用于确保你在应用开发中所需的数据一致性。 - -如果你不确定什么是 **乐观事务**,请 **_暂时不要_** 使用它。因为 **乐观事务** 需要应用能够正确处理 [`COMMIT`] 语句返回的 [所有错误](https://docs.pingcap.com/tidb/v8.5/error-codes/)。如果你不确定你的应用如何处理这些错误,建议使用 **悲观事务**。 - -## 应用与 TiDB 的交互方式 - -TiDB 高度兼容 MySQL 协议,支持 [大部分 MySQL 语法和功能](/mysql-compatibility.md),因此大多数 MySQL 连接库都可以兼容 TiDB。如果你的应用框架或语言没有 PingCAP 官方的适配器,建议使用 MySQL 的客户端库。越来越多的第三方库也在积极支持 TiDB 的不同特性。 - -由于 TiDB 兼容 MySQL 协议和语法,大部分支持 MySQL 的 ORM 也兼容 TiDB。 - -## 阅读更多 - -- [快速入门](/develop/dev-guide-build-cluster-in-cloud.md) -- [选择驱动或 ORM](/develop/dev-guide-choose-driver-or-orm.md) -- [连接 TiDB](https://docs.pingcap.com/tidb/v8.5/dev-guide-connect-to-tidb/) -- [数据库模式设计](/develop/dev-guide-schema-design-overview.md) -- [写入数据](/develop/dev-guide-insert-data.md) -- [读取数据](/develop/dev-guide-get-data-from-single-table.md) -- [事务](/develop/dev-guide-transaction-overview.md) -- [优化](/develop/dev-guide-optimize-sql-overview.md) -- [示例应用](/develop/dev-guide-sample-application-java-spring-boot.md) - -## 需要帮助? - -在 [Discord](https://discord.gg/DQZ2dy3cuc?utm_source=doc) 或 [Slack](https://slack.tidb.io/invite?team=tidb-community&channel=everyone&ref=pingcap-docs) 社区提问,或 [提交支持工单](https://docs.pingcap.com/tidb/v8.5/support/)。 - - \ No newline at end of file diff --git a/latest_translation_commit.json b/latest_translation_commit.json index bdcc3f5b1cc50..9756ca821167a 100644 --- a/latest_translation_commit.json +++ b/latest_translation_commit.json @@ -1 +1,4 @@ -{"target":"release-8.5","sha":"4b35531be680642691b5fe69a8cfb8a2ef4ccae6"} \ No newline at end of file +{ + "target": "release-8.5", + "sha": "26db3bfe2fccacf24422296da5022b42dc8d4682" +} \ No newline at end of file diff --git a/releases/release-notes.md b/releases/release-notes.md deleted file mode 100644 index b7f80305f412d..0000000000000 --- a/releases/release-notes.md +++ /dev/null @@ -1,302 +0,0 @@ ---- -title: Release Notes -summary: TiDB has released multiple versions, including 8.5.0, 8.4.0-DMR, 8.3.0-DMR, 8.2.0-DMR, 8.1.0, 8.0.0-DMR, 7.6.0-DMR, 7.5.1, 7.5.0, 7.4.0-DMR, 7.3.0-DMR, 7.2.0-DMR, 7.1.4, 7.1.3, 7.1.2, 7.1.1, 7.1.0, 7.0.0-DMR, 6.6.0-DMR, 6.5.9, 6.5.8, 6.5.7, 6.5.6, 6.5.5, 6.5.4, 6.5.3, 6.5.2, 6.5.1, 6.5.0, 6.4.0-DMR, 6.3.0-DMR, 6.2.0-DMR, 6.1.7, 6.1.6, 6.1.5, 6.1.4, 6.1.3, 6.1.2, 6.1.1, 6.1.0, 6.0.0-DMR, 5.4.3, 5.4.2, 5.4.1, 5.4.0, 5.3.4, 5.3.3, 5.3.2, 5.3.1, 5.3.0, 5.2.4, 5.2.3, 5.2.2, 5.2.1, 5.2.0, 5.1.5, 5.1.4, 5.1.3, 5.1.2, 5.1.1, 5.1.0, 5.0.6, 5.0.5, 5.0.4, 5.0.3, 5.0.2, 5.0.1, 5.0.0, 5.0.0-rc, 4.0.16, 4.0.15, 4.0.14, 4.0.13, 4.0.12, 4.0.11, 4.0.10, 4.0.9, 4.0.8, 4.0.7, 4.0.6, 4.0.5, 4.0.4, 4.0.3, 4.0.2, 4.0.1, 4.0.0, 4.0.0-rc.2, 4.0.0-rc.1, 4.0.0-rc, 4.0.0-beta.2, 4.0.0-beta.1, 4.0.0-beta, 3.1.2, 3.1.1, 3.1.0, 3.1.0-rc, 3.1.0-beta.2, 3.1.0-beta.1, 3.1.0-beta, 3.0.20, 3.0.19, 3.0.18, 3.0.17, 3.0.16, 3.0.15, 3.0.14, 3.0.13, 3.0.12, 3.0.11, 3.0.10, 3.0.9, 3.0.8, 3.0.7, 3.0.6, 3.0.5, 3.0.4, 3.0.3, 3.0.2, 3.0.1, 3.0.0, 3.0.0-rc.3, 3.0.0-rc.2, 3.0.0-rc.1, 3.0.0-beta.1, 3.0.0-beta, 2.1.19, 2.1.18, 2.1.17, 2.1.16, 2.1.15, 2.1.14, 2.1.13, 2.1.12, 2.1.11, 2.1.10, 2.1.9, 2.1.8, 2.1.7, 2.1.6, 2.1.5, 2.1.4, 2.1.3, 2.1.2, 2.1.1, 2.1.0, 2.1.0-rc.5, 2.1.0-rc.4, 2.1.0-rc.3, 2.1.0-rc.2, 2.1.0-rc.1, 2.1.0-beta, 2.0.11, 2.0.10, 2.0.9, 2.0.8, 2.0.7, 2.0.6, 2.0.5, 2.0.4, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 2.0.0-rc.5, 2.0.0-rc.4, 2.0.0-rc.3, 2.0.0-rc.1, 1.1.0-beta, 1.1.0-alpha, 1.0.8, 1.0.7, 1.0.6, 1.0.5, 1.0.4, 1.0.3, 1.0.2, 1.0.1, 1.0.0, Pre-GA, rc4, rc3, rc2, rc1. ---- - -# TiDB Release Notes - - - -This document lists all released TiDB versions, sorted by version number in descending order. - -To learn about the support timelines for Long-Term Support (LTS) versions of TiDB, see the [TiDB Release Support Policy](https://pingcap.com/tidb-release-support-policy/). - -## 8.5 - -- [8.5.2](/releases/release-8.5.2.md): 2025-06-12 -- [8.5.1](/releases/release-8.5.1.md): 2025-01-17 -- [8.5.0](/releases/release-8.5.0.md): 2024-12-19 - -## 8.4 - -- [8.4.0-DMR](/releases/release-8.4.0.md): 2024-11-11 - -## 8.3 - -- [8.3.0-DMR](/releases/release-8.3.0.md): 2024-08-22 - -## 8.2 - -- [8.2.0-DMR](/releases/release-8.2.0.md): 2024-07-11 - -## 8.1 - -- [8.1.2](/releases/release-8.1.2.md): 2024-12-26 -- [8.1.1](/releases/release-8.1.1.md): 2024-08-27 -- [8.1.0](/releases/release-8.1.0.md): 2024-05-24 - -## 8.0 - -- [8.0.0-DMR](/releases/release-8.0.0.md): 2024-03-29 - -## 7.6 - -- [7.6.0-DMR](/releases/release-7.6.0.md): 2024-01-25 - -## 7.5 - -- [7.5.6](/releases/release-7.5.6.md): 2025-03-14 -- [7.5.5](/releases/release-7.5.5.md): 2024-12-31 -- [7.5.4](/releases/release-7.5.4.md): 2024-10-15 -- [7.5.3](/releases/release-7.5.3.md): 2024-08-05 -- [7.5.2](/releases/release-7.5.2.md): 2024-06-13 -- [7.5.1](/releases/release-7.5.1.md): 2024-02-29 -- [7.5.0](/releases/release-7.5.0.md): 2023-12-01 - -## 7.4 - -- [7.4.0-DMR](/releases/release-7.4.0.md): 2023-10-12 - -## 7.3 - -- [7.3.0-DMR](/releases/release-7.3.0.md): 2023-08-14 - -## 7.2 - -- [7.2.0-DMR](/releases/release-7.2.0.md): 2023-06-29 - -## 7.1 - -- [7.1.6](/releases/release-7.1.6.md): 2024-11-21 -- [7.1.5](/releases/release-7.1.5.md): 2024-04-26 -- [7.1.4](/releases/release-7.1.4.md): 2024-03-11 -- [7.1.3](/releases/release-7.1.3.md): 2023-12-21 -- [7.1.2](/releases/release-7.1.2.md): 2023-10-25 -- [7.1.1](/releases/release-7.1.1.md): 2023-07-24 -- [7.1.0](/releases/release-7.1.0.md): 2023-05-31 - -## 7.0 - -- [7.0.0-DMR](/releases/release-7.0.0.md): 2023-03-30 - -## 6.6 - -- [6.6.0-DMR](/releases/release-6.6.0.md): 2023-02-20 - -## 6.5 - -- [6.5.12](/releases/release-6.5.12.md): 2025-02-27 -- [6.5.11](/releases/release-6.5.11.md): 2024-09-20 -- [6.5.10](/releases/release-6.5.10.md): 2024-06-20 -- [6.5.9](/releases/release-6.5.9.md): 2024-04-12 -- [6.5.8](/releases/release-6.5.8.md): 2024-02-02 -- [6.5.7](/releases/release-6.5.7.md): 2024-01-08 -- [6.5.6](/releases/release-6.5.6.md): 2023-12-07 -- [6.5.5](/releases/release-6.5.5.md): 2023-09-21 -- [6.5.4](/releases/release-6.5.4.md): 2023-08-28 -- [6.5.3](/releases/release-6.5.3.md): 2023-06-14 -- [6.5.2](/releases/release-6.5.2.md): 2023-04-21 -- [6.5.1](/releases/release-6.5.1.md): 2023-03-10 -- [6.5.0](/releases/release-6.5.0.md): 2022-12-29 - -## 6.4 - -- [6.4.0-DMR](/releases/release-6.4.0.md): 2022-11-17 - -## 6.3 - -- [6.3.0-DMR](/releases/release-6.3.0.md): 2022-09-30 - -## 6.2 - -- [6.2.0-DMR](/releases/release-6.2.0.md): 2022-08-23 - -## 6.1 - -- [6.1.7](/releases/release-6.1.7.md): 2023-07-12 -- [6.1.6](/releases/release-6.1.6.md): 2023-04-12 -- [6.1.5](/releases/release-6.1.5.md): 2023-02-28 -- [6.1.4](/releases/release-6.1.4.md): 2023-02-08 -- [6.1.3](/releases/release-6.1.3.md): 2022-12-05 -- [6.1.2](/releases/release-6.1.2.md): 2022-10-24 -- [6.1.1](/releases/release-6.1.1.md): 2022-09-01 -- [6.1.0](/releases/release-6.1.0.md): 2022-06-13 - -## 6.0 - -- [6.0.0-DMR](/releases/release-6.0.0-dmr.md): 2022-04-07 - -## 5.4 - -- [5.4.3](/releases/release-5.4.3.md): 2022-10-13 -- [5.4.2](/releases/release-5.4.2.md): 2022-07-08 -- [5.4.1](/releases/release-5.4.1.md): 2022-05-13 -- [5.4.0](/releases/release-5.4.0.md): 2022-02-15 - -## 5.3 - -- [5.3.4](/releases/release-5.3.4.md): 2022-11-24 -- [5.3.3](/releases/release-5.3.3.md): 2022-09-14 -- [5.3.2](/releases/release-5.3.2.md): 2022-06-29 -- [5.3.1](/releases/release-5.3.1.md): 2022-03-03 -- [5.3.0](/releases/release-5.3.0.md): 2021-11-30 - -## 5.2 - -- [5.2.4](/releases/release-5.2.4.md): 2022-04-26 -- [5.2.3](/releases/release-5.2.3.md): 2021-12-03 -- [5.2.2](/releases/release-5.2.2.md): 2021-10-29 -- [5.2.1](/releases/release-5.2.1.md): 2021-09-09 -- [5.2.0](/releases/release-5.2.0.md): 2021-08-27 - -## 5.1 - -- [5.1.5](/releases/release-5.1.5.md): 2022-12-28 -- [5.1.4](/releases/release-5.1.4.md): 2022-02-22 -- [5.1.3](/releases/release-5.1.3.md): 2021-12-03 -- [5.1.2](/releases/release-5.1.2.md): 2021-09-27 -- [5.1.1](/releases/release-5.1.1.md): 2021-07-30 -- [5.1.0](/releases/release-5.1.0.md): 2021-06-24 - -## 5.0 - -- [5.0.6](/releases/release-5.0.6.md): 2021-12-31 -- [5.0.5](/releases/release-5.0.5.md): 2021-12-03 -- [5.0.4](/releases/release-5.0.4.md): 2021-09-27 -- [5.0.3](/releases/release-5.0.3.md): 2021-07-02 -- [5.0.2](/releases/release-5.0.2.md): 2021-06-10 -- [5.0.1](/releases/release-5.0.1.md): 2021-04-24 -- [5.0.0](/releases/release-5.0.0.md): 2021-04-07 -- [5.0.0-rc](/releases/release-5.0.0-rc.md): 2021-01-12 - -## 4.0 - -- [4.0.16](/releases/release-4.0.16.md): 2021-12-17 -- [4.0.15](/releases/release-4.0.15.md): 2021-09-27 -- [4.0.14](/releases/release-4.0.14.md): 2021-07-27 -- [4.0.13](/releases/release-4.0.13.md): 2021-05-28 -- [4.0.12](/releases/release-4.0.12.md): 2021-04-02 -- [4.0.11](/releases/release-4.0.11.md): 2021-02-26 -- [4.0.10](/releases/release-4.0.10.md): 2021-01-15 -- [4.0.9](/releases/release-4.0.9.md): 2020-12-21 -- [4.0.8](/releases/release-4.0.8.md): 2020-10-30 -- [4.0.7](/releases/release-4.0.7.md): 2020-09-29 -- [4.0.6](/releases/release-4.0.6.md): 2020-09-15 -- [4.0.5](/releases/release-4.0.5.md): 2020-08-31 -- [4.0.4](/releases/release-4.0.4.md): 2020-07-31 -- [4.0.3](/releases/release-4.0.3.md): 2020-07-24 -- [4.0.2](/releases/release-4.0.2.md): 2020-07-01 -- [4.0.1](/releases/release-4.0.1.md): 2020-06-12 -- [4.0.0](/releases/release-4.0-ga.md): 2020-05-28 -- [4.0.0-rc.2](/releases/release-4.0.0-rc.2.md): 2020-05-15 -- [4.0.0-rc.1](/releases/release-4.0.0-rc.1.md): 2020-04-28 -- [4.0.0-rc](/releases/release-4.0.0-rc.md): 2020-04-08 -- [4.0.0-beta.2](/releases/release-4.0.0-beta.2.md): 2020-03-18 -- [4.0.0-beta.1](/releases/release-4.0.0-beta.1.md): 2020-02-28 -- [4.0.0-beta](/releases/release-4.0.0-beta.md): 2020-01-17 - -## 3.1 - -- [3.1.2](/releases/release-3.1.2.md): 2020-06-04 -- [3.1.1](/releases/release-3.1.1.md): 2020-04-30 -- [3.1.0](/releases/release-3.1.0-ga.md): 2020-04-16 -- [3.1.0-rc](/releases/release-3.1.0-rc.md): 2020-04-02 -- [3.1.0-beta.2](/releases/release-3.1.0-beta.2.md): 2020-03-09 -- [3.1.0-beta.1](/releases/release-3.1.0-beta.1.md): 2020-01-10 -- [3.1.0-beta](/releases/release-3.1.0-beta.md): 2019-12-20 - -## 3.0 - -- [3.0.20](/releases/release-3.0.20.md): 2020-12-25 -- [3.0.19](/releases/release-3.0.19.md): 2020-09-25 -- [3.0.18](/releases/release-3.0.18.md): 2020-08-21 -- [3.0.17](/releases/release-3.0.17.md): 2020-08-03 -- [3.0.16](/releases/release-3.0.16.md): 2020-07-03 -- [3.0.15](/releases/release-3.0.15.md): 2020-06-05 -- [3.0.14](/releases/release-3.0.14.md): 2020-05-09 -- [3.0.13](/releases/release-3.0.13.md): 2020-04-22 -- [3.0.12](/releases/release-3.0.12.md): 2020-03-16 -- [3.0.11](/releases/release-3.0.11.md): 2020-03-04 -- [3.0.10](/releases/release-3.0.10.md): 2020-02-20 -- [3.0.9](/releases/release-3.0.9.md): 2020-01-14 -- [3.0.8](/releases/release-3.0.8.md): 2019-12-31 -- [3.0.7](/releases/release-3.0.7.md): 2019-12-04 -- [3.0.6](/releases/release-3.0.6.md): 2019-11-28 -- [3.0.5](/releases/release-3.0.5.md): 2019-10-25 -- [3.0.4](/releases/release-3.0.4.md): 2019-10-08 -- [3.0.3](/releases/release-3.0.3.md): 2019-08-29 -- [3.0.2](/releases/release-3.0.2.md): 2019-08-07 -- [3.0.1](/releases/release-3.0.1.md): 2019-07-16 -- [3.0.0](/releases/release-3.0-ga.md): 2019-06-28 -- [3.0.0-rc.3](/releases/release-3.0.0-rc.3.md): 2019-06-21 -- [3.0.0-rc.2](/releases/release-3.0.0-rc.2.md): 2019-05-28 -- [3.0.0-rc.1](/releases/release-3.0.0-rc.1.md): 2019-05-10 -- [3.0.0-beta.1](/releases/release-3.0.0-beta.1.md): 2019-03-26 -- [3.0.0-beta](/releases/release-3.0-beta.md): 2019-01-19 - -## 2.1 - -- [2.1.19](/releases/release-2.1.19.md): 2019-12-27 -- [2.1.18](/releases/release-2.1.18.md): 2019-11-04 -- [2.1.17](/releases/release-2.1.17.md): 2019-09-11 -- [2.1.16](/releases/release-2.1.16.md): 2019-08-15 -- [2.1.15](/releases/release-2.1.15.md): 2019-07-18 -- [2.1.14](/releases/release-2.1.14.md): 2019-07-04 -- [2.1.13](/releases/release-2.1.13.md): 2019-06-21 -- [2.1.12](/releases/release-2.1.12.md): 2019-06-13 -- [2.1.11](/releases/release-2.1.11.md): 2019-06-03 -- [2.1.10](/releases/release-2.1.10.md): 2019-05-22 -- [2.1.9](/releases/release-2.1.9.md): 2019-05-06 -- [2.1.8](/releases/release-2.1.8.md): 2019-04-12 -- [2.1.7](/releases/release-2.1.7.md): 2019-03-28 -- [2.1.6](/releases/release-2.1.6.md): 2019-03-15 -- [2.1.5](/releases/release-2.1.5.md): 2019-02-28 -- [2.1.4](/releases/release-2.1.4.md): 2019-02-15 -- [2.1.3](/releases/release-2.1.3.md): 2019-01-28 -- [2.1.2](/releases/release-2.1.2.md): 2018-12-22 -- [2.1.1](/releases/release-2.1.1.md): 2018-12-12 -- [2.1.0](/releases/release-2.1-ga.md): 2018-11-30 -- [2.1.0-rc.5](/releases/release-2.1-rc.5.md): 2018-11-12 -- [2.1.0-rc.4](/releases/release-2.1-rc.4.md): 2018-10-23 -- [2.1.0-rc.3](/releases/release-2.1-rc.3.md): 2018-09-29 -- [2.1.0-rc.2](/releases/release-2.1-rc.2.md): 2018-09-14 -- [2.1.0-rc.1](/releases/release-2.1-rc.1.md): 2018-08-24 -- [2.1.0-beta](/releases/release-2.1-beta.md): 2018-06-29 - -## 2.0 - -- [2.0.11](/releases/release-2.0.11.md): 2019-01-03 -- [2.0.10](/releases/release-2.0.10.md): 2018-12-18 -- [2.0.9](/releases/release-2.0.9.md): 2018-11-19 -- [2.0.8](/releases/release-2.0.8.md): 2018-10-16 -- [2.0.7](/releases/release-2.0.7.md): 2018-09-07 -- [2.0.6](/releases/release-2.0.6.md): 2018-08-06 -- [2.0.5](/releases/release-2.0.5.md): 2018-07-06 -- [2.0.4](/releases/release-2.0.4.md): 2018-06-15 -- [2.0.3](/releases/release-2.0.3.md): 2018-06-01 -- [2.0.2](/releases/release-2.0.2.md): 2018-05-21 -- [2.0.1](/releases/release-2.0.1.md): 2018-05-16 -- [2.0.0](/releases/release-2.0-ga.md): 2018-04-27 -- [2.0.0-rc.5](/releases/release-2.0-rc.5.md): 2018-04-17 -- [2.0.0-rc.4](/releases/release-2.0-rc.4.md): 2018-03-30 -- [2.0.0-rc.3](/releases/release-2.0-rc.3.md): 2018-03-23 -- [2.0.0-rc.1](/releases/release-2.0-rc.1.md): 2018-03-09 -- [1.1.0-beta](/releases/release-1.1-beta.md): 2018-02-24 -- [1.1.0-alpha](/releases/release-1.1-alpha.md): 2018-01-19 - -## 1.0 - -- [1.0.8](/releases/release-1.0.8.md): 2018-02-11 -- [1.0.7](/releases/release-1.0.7.md): 2018-01-22 -- [1.0.6](/releases/release-1.0.6.md): 2018-01-08 -- [1.0.5](/releases/release-1.0.5.md): 2017-12-26 -- [1.0.4](/releases/release-1.0.4.md): 2017-12-11 -- [1.0.3](/releases/release-1.0.3.md): 2017-11-28 -- [1.0.2](/releases/release-1.0.2.md): 2017-11-13 -- [1.0.1](/releases/release-1.0.1.md): 2017-11-01 -- [1.0.0](/releases/release-1.0-ga.md): 2017-10-16 -- [Pre-GA](/releases/release-pre-ga.md): 2017-08-30 -- [rc4](/releases/release-rc.4.md): 2017-08-04 -- [rc3](/releases/release-rc.3.md): 2017-06-16 -- [rc2](/releases/release-rc.2.md): 2017-03-01 -- [rc1](/releases/release-rc.1.md): 2016-12-23 diff --git a/tidb-cloud/api-overview.md b/tidb-cloud/api-overview.md deleted file mode 100644 index e31333afdadbf..0000000000000 --- a/tidb-cloud/api-overview.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: TiDB Cloud API Overview -summary: 了解什么是 TiDB Cloud API、其功能,以及如何使用 API 管理你的 TiDB Cloud 集群。 ---- - -# TiDB Cloud API 概览(Beta) - -> **Note:** -> -> TiDB Cloud API 目前处于 beta 阶段。 - -TiDB Cloud API 是一个 [REST 接口](https://en.wikipedia.org/wiki/Representational_state_transfer),为你提供以编程方式管理 TiDB Cloud 内部管理对象的能力。通过该 API,你可以自动且高效地管理诸如项目、集群、备份、恢复、导入、计费以及 [Data Service](/tidb-cloud/data-service-overview.md) 中的资源等。 - -该 API 具有以下特性: - -- **JSON entities.** 所有实体均以 JSON 格式表示。 -- **HTTPS-only.** 你只能通过 HTTPS 访问该 API,确保所有通过网络传输的数据都经过 TLS 加密。 -- **Key-based access and digest authentication.** 在访问 TiDB Cloud API 之前,你必须生成一个 API key,参考 [API Key Management](https://docs.pingcap.com/tidbcloud/api/v1beta#section/Authentication/API-key-management)。所有请求都通过 [HTTP Digest Authentication](https://en.wikipedia.org/wiki/Digest_access_authentication) 进行身份验证,确保 API key 永远不会在网络上传输。 - -TiDB Cloud API 提供以下两个版本: - -- v1beta1 - - 集群级资源: - - [TiDB Cloud Starter 或 Essential 集群](https://docs.pingcap.com/tidbcloud/api/v1beta1/serverless):管理 TiDB Cloud Starter 或 Essential 集群的集群、分支、数据导出任务和数据导入任务。 - - [TiDB Cloud Dedicated 集群](https://docs.pingcap.com/tidbcloud/api/v1beta1/dedicated):管理 TiDB Cloud Dedicated 集群的集群、区域、私有端点连接和数据导入任务。 - - 组织或项目级资源: - - [Billing](https://docs.pingcap.com/tidbcloud/api/v1beta1/billing):管理 TiDB Cloud 集群的计费。 - - [Data Service](https://docs.pingcap.com/tidbcloud/api/v1beta1/dataservice):管理 TiDB Cloud 集群中 Data Service 的资源。 - - [IAM](https://docs.pingcap.com/tidbcloud/api/v1beta1/iam):管理 TiDB Cloud 集群的 API key。 - - [MSP (Deprecated)](https://docs.pingcap.com/tidbcloud/api/v1beta1/msp) -- [v1beta](https://docs.pingcap.com/tidbcloud/api/v1beta) - - [Project](https://docs.pingcap.com/tidbcloud/api/v1beta/#tag/Project) - - [Cluster](https://docs.pingcap.com/tidbcloud/api/v1beta/#tag/Cluster) - - [Backup](https://docs.pingcap.com/tidbcloud/api/v1beta/#tag/Backup) - - [Import (Deprecated)](https://docs.pingcap.com/tidbcloud/api/v1beta/#tag/Import) - - [Restore](https://docs.pingcap.com/tidbcloud/api/v1beta/#tag/Restore) \ No newline at end of file diff --git a/tidb-cloud/dev-guide-wordpress.md b/tidb-cloud/dev-guide-wordpress.md deleted file mode 100644 index 34feb5f80d562..0000000000000 --- a/tidb-cloud/dev-guide-wordpress.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: 使用 WordPress 连接 TiDB Cloud Starter -summary: 学习如何使用 TiDB Cloud Starter 运行 WordPress。本教程将为你提供分步指导,让你在几分钟内运行 WordPress + TiDB Cloud Starter。 ---- - -# 使用 WordPress 连接 TiDB Cloud Starter - -TiDB 是一个兼容 MySQL 的数据库,TiDB Cloud Starter 是一款全托管的 TiDB 云服务,[WordPress](https://github.com/WordPress) 是一个免费的开源内容管理系统(CMS),可以让用户创建和管理网站。WordPress 使用 PHP 编写,并使用 MySQL 数据库。 - -在本教程中,你可以学习如何免费使用 TiDB Cloud Starter 运行 WordPress。 - -> **Note:** -> -> 除了 TiDB Cloud Starter,本教程同样适用于 TiDB Cloud Essential、TiDB Cloud Dedicated 以及 TiDB 自建集群。但强烈推荐使用 TiDB Cloud Starter 来运行 WordPress,以获得更高的性价比。 - -## 前置条件 - -完成本教程,你需要: - -- 一个 TiDB Cloud Starter 集群。如果你还没有集群,请按照[创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md)来创建属于你自己的 TiDB Cloud 集群。 - -## 使用 TiDB Cloud Starter 运行 WordPress - -本节将演示如何使用 TiDB Cloud Starter 运行 WordPress。 - -### 第 1 步:克隆 WordPress 示例仓库 - -在终端窗口中运行以下命令,克隆示例代码仓库: - -```shell -git clone https://github.com/Icemap/wordpress-tidb-docker.git -cd wordpress-tidb-docker -``` - -### 第 2 步:安装依赖 - -1. 示例仓库需要 [Docker](https://www.docker.com/) 和 [Docker Compose](https://docs.docker.com/compose/) 来启动 WordPress。如果你已经安装了它们,可以跳过此步骤。强烈建议你在 Linux 环境(如 Ubuntu)下运行 WordPress。运行以下命令安装 Docker 和 Docker Compose: - - ```shell - sudo sh install.sh - ``` - -2. 示例仓库包含了 [TiDB Compatibility Plugin](https://github.com/pingcap/wordpress-tidb-plugin) 作为子模块。运行以下命令以更新子模块: - - ```shell - git submodule update --init --recursive - ``` - -### 第 3 步:配置连接信息 - -配置 WordPress 数据库连接到 TiDB Cloud Starter。 - -1. 进入 [**Clusters**](https://tidbcloud.com/project/clusters) 页面,然后点击目标集群的名称,进入其概览页面。 - -2. 点击右上角的 **Connect**。此时会弹出连接对话框。 - -3. 确保连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public`。 - - **Connect With** 设置为 `WordPress`。 - - **Operating System** 设置为 `Debian/Ubuntu/Arch`。 - - **Database** 设置为你想要使用的数据库,例如 `test`。 - -4. 点击 **Generate Password** 生成一个随机密码。 - - > **Tip:** - > - > 如果你之前已经创建过密码,可以继续使用原有密码,或者点击 **Reset Password** 生成新密码。 - -5. 运行以下命令,将 `.env.example` 复制并重命名为 `.env`: - - ```shell - cp .env.example .env - ``` - -6. 将对应的连接字符串复制粘贴到 `.env` 文件中。示例结果如下: - - ```dotenv - TIDB_HOST='{HOST}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com - TIDB_PORT='4000' - TIDB_USER='{USERNAME}' # e.g. xxxxxx.root - TIDB_PASSWORD='{PASSWORD}' - TIDB_DB_NAME='test' - ``` - - 请确保将 `{}` 占位符替换为你在连接对话框中获得的连接参数。默认情况下,你的 TiDB Cloud Starter 自带一个 `test` 数据库。如果你已经在 TiDB Cloud Starter 集群中创建了其他数据库,可以将 `test` 替换为你的数据库名。 - -7. 保存 `.env` 文件。 - -### 第 4 步:使用 TiDB Cloud Starter 启动 WordPress - -1. 执行以下命令,将 WordPress 作为 Docker 容器运行: - - ```shell - docker compose up -d - ``` - -2. 通过访问 [localhost](http://localhost/)(如果你在本地机器上启动容器)或 `http://`(如果 WordPress 运行在远程机器上)来设置你的 WordPress 站点。 - -### 第 5 步:确认数据库连接 - -1. 在 TiDB Cloud 控制台关闭集群的连接对话框,并打开 **SQL Editor** 页面。 -2. 在左侧的 **Schemas** 标签下,点击你连接到 WordPress 的数据库。 -3. 确认你现在可以在该数据库的表列表中看到 WordPress 的表(如 `wp_posts` 和 `wp_comments`)。 - -## 需要帮助? - -你可以在 [Discord](https://discord.gg/DQZ2dy3cuc?utm_source=doc) 或 [Slack](https://slack.tidb.io/invite?team=tidb-community&channel=everyone&ref=pingcap-docs) 社区提问,或[提交支持工单](https://tidb.support.pingcap.com/)。 \ No newline at end of file diff --git a/tidb-cloud/serverless-driver-drizzle-example.md b/tidb-cloud/serverless-driver-drizzle-example.md deleted file mode 100644 index 1c8dde6e8dcb3..0000000000000 --- a/tidb-cloud/serverless-driver-drizzle-example.md +++ /dev/null @@ -1,272 +0,0 @@ ---- -title: TiDB Cloud Serverless Driver Drizzle 教程 -summary: 学习如何在 Drizzle 中使用 TiDB Cloud serverless driver。 ---- - -# TiDB Cloud Serverless Driver Drizzle 教程 - -[Drizzle ORM](https://orm.drizzle.team/) 是一款轻量级且高性能的 TypeScript ORM,注重开发者体验。从 `drizzle-orm@0.31.2` 开始,Drizzle 支持 [drizzle-orm/tidb-serverless](https://orm.drizzle.team/docs/get-started-mysql#tidb-serverless),你可以通过 [TiDB Cloud serverless driver](/tidb-cloud/serverless-driver.md) 以 HTTPS 方式连接 Drizzle。 - -本教程介绍如何在 Node.js 环境和边缘环境中,将 TiDB Cloud serverless driver 与 Drizzle 搭配使用。 - -## 在 Node.js 环境中使用 Drizzle 和 TiDB Cloud serverless driver - -本节介绍如何在 Node.js 环境中,将 TiDB Cloud serverless driver 与 Drizzle 搭配使用。 - -### 前置条件 - -完成本教程,你需要准备以下内容: - -- [Node.js](https://nodejs.org/en) >= 18.0.0。 -- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器。 -- 一个 TiDB Cloud Serverless 集群。如果你还没有,可以[创建一个 TiDB Cloud Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md)。 - -### 步骤 1. 创建项目 - -1. 创建一个名为 `drizzle-node-example` 的项目: - - ```shell - mkdir drizzle-node-example - cd drizzle-node-example - ``` - -2. 安装 `drizzle-orm` 和 `@tidbcloud/serverless` 包: - - ```shell - npm install drizzle-orm @tidbcloud/serverless - ``` - -3. 在项目根目录下,找到 `package.json` 文件,并通过添加 `"type": "module"` 指定 ES module: - - ```json - { - "type": "module", - "dependencies": { - "@tidbcloud/serverless": "^0.1.1", - "drizzle-orm": "^0.31.2" - } - } - ``` - -4. 在项目根目录下,添加 `tsconfig.json` 文件以定义 TypeScript 编译选项。以下是示例文件: - - ```json - { - "compilerOptions": { - "module": "ES2022", - "target": "ES2022", - "moduleResolution": "node", - "strict": false, - "declaration": true, - "outDir": "dist", - "removeComments": true, - "allowJs": true, - "esModuleInterop": true, - "resolveJsonModule": true - } - } - ``` - -### 步骤 2. 配置环境 - -1. 在 [TiDB Cloud 控制台](https://tidbcloud.com/)中,进入你项目的 [**Clusters**](https://tidbcloud.com/project/clusters) 页面,点击目标 TiDB Cloud Serverless 集群名称,进入集群概览页。 - -2. 在概览页右上角点击 **Connect**,在 **Connect With** 下拉列表中选择 `Serverless Driver`,然后点击 **Generate Password** 生成随机密码。 - - > **Tip:** - > - > 如果你之前已经创建过密码,可以继续使用原密码,或者点击 **Reset Password** 生成新密码。 - - 连接字符串格式如下: - - ``` - mysql://[username]:[password]@[host]/[database] - ``` - -3. 在本地环境中设置环境变量 `DATABASE_URL`。例如,在 Linux 或 macOS 下,可以运行以下命令: - - ```shell - export DATABASE_URL='mysql://[username]:[password]@[host]/[database]' - ``` - -### 步骤 3. 使用 Drizzle 查询数据 - -1. 在你的 TiDB Cloud Serverless 集群中创建一张表。 - - 你可以使用 [TiDB Cloud 控制台的 SQL Editor](/tidb-cloud/explore-data-with-chat2query.md) 执行 SQL 语句。以下为示例: - - ```sql - CREATE TABLE `test`.`users` ( - `id` BIGINT PRIMARY KEY auto_increment, - `full_name` TEXT, - `phone` VARCHAR(256) - ); - ``` - -2. 在项目根目录下,创建名为 `hello-world.ts` 的文件,并添加以下代码: - - ```ts - import { connect } from '@tidbcloud/serverless'; - import { drizzle } from 'drizzle-orm/tidb-serverless'; - import { mysqlTable, serial, text, varchar } from 'drizzle-orm/mysql-core'; - - // Initialize - const client = connect({ url: process.env.DATABASE_URL }); - const db = drizzle(client); - - // Define schema - export const users = mysqlTable('users', { - id: serial("id").primaryKey(), - fullName: text('full_name'), - phone: varchar('phone', { length: 256 }), - }); - export type User = typeof users.$inferSelect; // return type when queried - export type NewUser = typeof users.$inferInsert; // insert type - - // Insert and select data - const user: NewUser = { fullName: 'John Doe', phone: '123-456-7890' }; - await db.insert(users).values(user) - const result: User[] = await db.select().from(users); - console.log(result); - ``` - -### 步骤 4. 运行 Typescript 代码 - -1. 安装 `ts-node` 用于将 TypeScript 转换为 JavaScript,并安装 `@types/node` 以为 Node.js 提供 TypeScript 类型定义。 - - ```shell - npm install -g ts-node - npm i --save-dev @types/node - ``` - -2. 使用以下命令运行 Typescript 代码: - - ```shell - ts-node --esm hello-world.ts - ``` - -## 在边缘环境中使用 Drizzle 和 TiDB Cloud serverless driver - -本节以 Vercel Edge Function 为例进行说明。 - -### 前置条件 - -完成本教程,你需要准备以下内容: - -- 一个支持边缘环境的 [Vercel](https://vercel.com/docs) 账号。 -- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器。 -- 一个 TiDB Cloud Serverless 集群。如果你还没有,可以[创建一个 TiDB Cloud Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md)。 - -### 步骤 1. 创建项目 - -1. 安装 Vercel CLI: - - ```shell - npm i -g vercel@latest - ``` - -2. 使用以下命令创建一个名为 `drizzle-example` 的 [Next.js](https://nextjs.org/) 项目: - - ```shell - npx create-next-app@latest drizzle-example --ts --no-eslint --tailwind --no-src-dir --app --import-alias "@/*" - ``` - -3. 进入 `drizzle-example` 目录: - - ```shell - cd drizzle-example - ``` - -4. 安装 `drizzle-orm` 和 `@tidbcloud/serverless` 包: - - ```shell - npm install drizzle-orm @tidbcloud/serverless --force - ``` - -### 步骤 2. 配置环境 - -1. 在 [TiDB Cloud 控制台](https://tidbcloud.com/)中,进入你项目的 [**Clusters**](https://tidbcloud.com/project/clusters) 页面,点击目标 TiDB Cloud Serverless 集群名称,进入集群概览页。 - -2. 在概览页右上角点击 **Connect**,在 **Connect With** 下拉列表中选择 `Serverless Driver`,然后点击 **Generate Password** 生成随机密码。 - - > **Tip:** - > - > 如果你之前已经创建过密码,可以继续使用原密码,或者点击 **Reset Password** 生成新密码。 - - 连接字符串格式如下: - - ``` - mysql://[username]:[password]@[host]/[database] - ``` - -### 步骤 3. 创建边缘函数 - -1. 在你的 TiDB Cloud Serverless 集群中创建一张表。 - - 你可以使用 [TiDB Cloud 控制台的 SQL Editor](/tidb-cloud/explore-data-with-chat2query.md) 执行 SQL 语句。以下为示例: - - ```sql - CREATE TABLE `test`.`users` ( - `id` BIGINT PRIMARY KEY auto_increment, - `full_name` TEXT, - `phone` VARCHAR(256) - ); - ``` - -2. 在项目的 `app` 目录下,创建文件 `/api/edge-function-example/route.ts`,并添加以下代码: - - ```ts - import { NextResponse } from 'next/server'; - import type { NextRequest } from 'next/server'; - import { connect } from '@tidbcloud/serverless'; - import { drizzle } from 'drizzle-orm/tidb-serverless'; - import { mysqlTable, serial, text, varchar } from 'drizzle-orm/mysql-core'; - export const runtime = 'edge'; - - // Initialize - const client = connect({ url: process.env.DATABASE_URL }); - const db = drizzle(client); - - // Define schema - export const users = mysqlTable('users', { - id: serial("id").primaryKey(), - fullName: text('full_name'), - phone: varchar('phone', { length: 256 }), - }); - export type User = typeof users.$inferSelect; // return type when queried - export type NewUser = typeof users.$inferInsert; // insert type - - export async function GET(request: NextRequest) { - // Insert and select data - const user: NewUser = { fullName: 'John Doe', phone: '123-456-7890' }; - await db.insert(users).values(user) - const result: User[] = await db.select().from(users); - return NextResponse.json(result); - } - ``` - -3. 本地测试你的代码: - - ```shell - export DATABASE_URL='mysql://[username]:[password]@[host]/[database]' - next dev - ``` - -4. 访问 `http://localhost:3000/api/edge-function-example`,获取路由返回的响应。 - -### 步骤 4. 部署代码到 Vercel - -1. 使用 `DATABASE_URL` 环境变量将代码部署到 Vercel: - - ```shell - vercel -e DATABASE_URL='mysql://[username]:[password]@[host]/[database]' --prod - ``` - - 部署完成后,你会获得项目的 URL。 - -2. 访问 `${Your-URL}/api/edge-function-example` 页面,获取路由返回的响应。 - -## 后续操作 - -- 了解更多关于 [Drizzle](https://orm.drizzle.team/docs/overview) 和 [drizzle-orm/tidb-serverless](https://orm.drizzle.team/docs/get-started-mysql#tidb-serverless) 的信息。 -- 学习如何 [集成 TiDB Cloud 与 Vercel](/tidb-cloud/integrate-tidbcloud-with-vercel.md)。 \ No newline at end of file diff --git a/tidb-cloud/serverless-driver-kysely-example.md b/tidb-cloud/serverless-driver-kysely-example.md deleted file mode 100644 index bb05f71169f74..0000000000000 --- a/tidb-cloud/serverless-driver-kysely-example.md +++ /dev/null @@ -1,299 +0,0 @@ ---- -title: TiDB Cloud Serverless Driver Kysely 教程 -summary: 学习如何在 Kysely 中使用 TiDB Cloud serverless driver。 ---- - -# TiDB Cloud Serverless Driver Kysely 教程 - -[Kysely](https://kysely.dev/docs/intro) 是一个类型安全且支持自动补全的 TypeScript SQL 查询构建器。TiDB Cloud 提供了 [@tidbcloud/kysely](https://github.com/tidbcloud/kysely),使你能够通过 [TiDB Cloud serverless driver](/tidb-cloud/serverless-driver.md) 在 HTTPS 上使用 Kysely。与传统的 TCP 方式相比,[ @tidbcloud/kysely ](https://github.com/tidbcloud/kysely) 带来了以下优势: - -- 在 serverless 环境下拥有更好的性能。 -- 能够在 edge 环境中使用 Kysely。 - -本教程介绍了如何在 Node.js 环境和 edge 环境中,将 TiDB Cloud serverless driver 与 Kysely 结合使用。 - -## 在 Node.js 环境中使用 TiDB Cloud Kysely 方言 - -本节介绍如何在 Node.js 环境中,将 TiDB Cloud serverless driver 与 Kysely 结合使用。 - -### 前置条件 - -完成本教程,你需要: - -- [Node.js](https://nodejs.org/en) >= 18.0.0。 -- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器。 -- 一个 TiDB Cloud Serverless 集群。如果你还没有,可以[创建一个 TiDB Cloud Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md)。 - -### 步骤 1. 创建项目 - -1. 创建一个名为 `kysely-node-example` 的项目: - - ``` - mkdir kysely-node-example - cd kysely-node-example - ``` - -2. 安装 `kysely`、`@tidbcloud/kysely` 和 `@tidbcloud/serverless` 包: - - ``` - npm install kysely @tidbcloud/kysely @tidbcloud/serverless - ``` - -3. 在项目根目录下,找到 `package.json` 文件,并通过添加 `"type": "module"` 指定 ES module: - - ```json - { - "type": "module", - "dependencies": { - "@tidbcloud/kysely": "^0.0.4", - "@tidbcloud/serverless": "^0.0.7", - "kysely": "^0.26.3", - } - } - ``` - -4. 在项目根目录下,添加 `tsconfig.json` 文件以定义 TypeScript 编译选项。以下是示例文件: - - ```json - { - "compilerOptions": { - "module": "ES2022", - "target": "ES2022", - "moduleResolution": "node", - "strict": false, - "declaration": true, - "outDir": "dist", - "removeComments": true, - "allowJs": true, - "esModuleInterop": true, - "resolveJsonModule": true - } - } - ``` - -### 步骤 2. 设置环境 - -1. 在 TiDB Cloud Serverless 集群的 overview 页面,点击右上角的 **Connect**,然后在弹出的对话框中获取你的数据库连接字符串。连接字符串格式如下: - - ``` - mysql://[username]:[password]@[host]/[database] - ``` - -2. 在本地环境中设置环境变量 `DATABASE_URL`。例如,在 Linux 或 macOS 下,可以运行以下命令: - - ```bash - export DATABASE_URL='mysql://[username]:[password]@[host]/[database]' - ``` - -### 步骤 3. 使用 Kysely 查询数据 - -1. 在你的 TiDB Cloud Serverless 集群中创建一张表并插入一些数据。 - - 你可以使用 [TiDB Cloud 控制台中的 SQL Editor](/tidb-cloud/explore-data-with-chat2query.md) 执行 SQL 语句。以下为示例: - - ```sql - CREATE TABLE `test`.`person` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(255) NULL DEFAULT NULL, - `gender` enum('male','female') NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE - ); - - insert into test.person values (1,'pingcap','male') - ``` - -2. 在项目根目录下,创建名为 `hello-world.ts` 的文件,并添加以下代码: - - ```ts - import { Kysely,GeneratedAlways,Selectable } from 'kysely' - import { TiDBServerlessDialect } from '@tidbcloud/kysely' - - // Types - interface Database { - person: PersonTable - } - - interface PersonTable { - id: GeneratedAlways - name: string - gender: "male" | "female" - } - - // Dialect - const db = new Kysely({ - dialect: new TiDBServerlessDialect({ - url: process.env.DATABASE_URL - }), - }) - - // Simple Querying - type Person = Selectable - export async function findPeople(criteria: Partial = {}) { - let query = db.selectFrom('person') - - if (criteria.name){ - query = query.where('name', '=', criteria.name) - } - - return await query.selectAll().execute() - } - - console.log(await findPeople()) - ``` - -### 步骤 4. 运行 Typescript 代码 - -1. 安装 `ts-node` 用于将 TypeScript 转换为 JavaScript,并安装 `@types/node` 以为 Node.js 提供 TypeScript 类型定义。 - - ``` - npm install -g ts-node - npm i --save-dev @types/node - ``` - -2. 使用以下命令运行 Typescript 代码: - - ``` - ts-node --esm hello-world.ts - ``` - -## 在 edge 环境中使用 TiDB Cloud Kysely 方言 - -本节以 Vercel Edge Function 中的 TiDB Cloud Kysely 方言为例进行说明。 - -### 前置条件 - -完成本教程,你需要: - -- 一个提供 edge 环境的 [Vercel](https://vercel.com/docs) 账号。 -- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器。 -- 一个 TiDB Cloud Serverless 集群。如果你还没有,可以[创建一个 TiDB Cloud Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md)。 - -### 步骤 1. 创建项目 - -1. 安装 Vercel CLI: - - ``` - npm i -g vercel@latest - ``` - -2. 使用以下终端命令创建一个名为 `kysely-example` 的 [Next.js](https://nextjs.org/) 项目: - - ``` - npx create-next-app@latest kysely-example --ts --no-eslint --tailwind --no-src-dir --app --import-alias "@/*" - cd kysely-example - ``` - -3. 安装 `kysely`、`@tidbcloud/kysely` 和 `@tidbcloud/serverless` 包: - - ``` - npm install kysely @tidbcloud/kysely @tidbcloud/serverless - ``` - -### 步骤 2. 设置环境 - -在 TiDB Cloud Serverless 集群的 overview 页面,点击右上角的 **Connect**,然后在弹出的对话框中获取你的数据库连接字符串。连接字符串格式如下: - -``` -mysql://[username]:[password]@[host]/[database] -``` - -### 步骤 3. 创建 edge function - -1. 在你的 TiDB Cloud Serverless 集群中创建一张表并插入一些数据。 - - 你可以使用 [TiDB Cloud 控制台中的 SQL Editor](/tidb-cloud/explore-data-with-chat2query.md) 执行 SQL 语句。以下为示例: - - ```sql - CREATE TABLE `test`.`person` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(255) NULL DEFAULT NULL, - `gender` enum('male','female') NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE - ); - - insert into test.person values (1,'pingcap','male') - ``` - -2. 在项目的 `app` 目录下,创建文件 `/api/edge-function-example/route.ts`,并添加以下代码: - - ```ts - import { NextResponse } from 'next/server'; - import type { NextRequest } from 'next/server'; - import { Kysely,GeneratedAlways,Selectable } from 'kysely' - import { TiDBServerlessDialect } from '@tidbcloud/kysely' - - export const runtime = 'edge'; - - // Types - interface Database { - person: PersonTable - } - - interface PersonTable { - id: GeneratedAlways - name: string - gender: "male" | "female" | "other" - } - - // Dialect - const db = new Kysely({ - dialect: new TiDBServerlessDialect({ - url: process.env.DATABASE_URL - }), - }) - - // Query - type Person = Selectable - async function findPeople(criteria: Partial = {}) { - let query = db.selectFrom('person') - - if (criteria.name){ - query = query.where('name', '=', criteria.name) - } - - return await query.selectAll().execute() - } - - export async function GET(request: NextRequest) { - - const searchParams = request.nextUrl.searchParams - const query = searchParams.get('query') - - let response = null; - if (query) { - response = await findPeople({name: query}) - } else { - response = await findPeople() - } - - return NextResponse.json(response); - } - ``` - - 上述代码接收一个查询参数 `query` 并返回查询结果。如果未提供该参数,则返回 `person` 表中的所有记录。 - -3. 本地测试你的代码: - - ``` - export DATABASE_URL='mysql://[username]:[password]@[host]/[database]' - next dev - ``` - -4. 访问 `http://localhost:3000/api/edge-function-example`,即可获取该路由的响应。 - -### 步骤 4. 部署代码到 Vercel - -1. 使用 `DATABASE_URL` 环境变量将代码部署到 Vercel: - - ``` - vercel -e DATABASE_URL='mysql://[username]:[password]@[host]/[database]' --prod - ``` - - 部署完成后,你将获得项目的 URL。 - -2. 访问 `${Your-URL}/api/edge-function-example` 页面,即可获取该路由的响应。 - -## 后续操作 - -- 了解更多关于 [Kysely](https://kysely.dev/docs/intro) 和 [@tidbcloud/kysely](https://github.com/tidbcloud/kysely) 的信息 -- 学习如何 [将 TiDB Cloud 集成到 Vercel](/tidb-cloud/integrate-tidbcloud-with-vercel.md) diff --git a/tidb-cloud/serverless-driver-node-example.md b/tidb-cloud/serverless-driver-node-example.md deleted file mode 100644 index 157a96e2b6829..0000000000000 --- a/tidb-cloud/serverless-driver-node-example.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: TiDB Cloud Serverless Driver Node.js 教程 -summary: 学习如何在本地 Node.js 项目中使用 TiDB Cloud serverless driver。 ---- - -# TiDB Cloud Serverless Driver Node.js 教程 - -本教程介绍如何在本地 Node.js 项目中使用 TiDB Cloud serverless driver。 - -> **Note:** -> -> - 本教程仅适用于 TiDB Cloud Serverless 集群。 -> - 如果你想了解如何在 Cloudflare Workers、Vercel Edge Functions 和 Netlify Edge Functions 中使用 TiDB Cloud serverless driver,请参考我们的 [Insights into Automotive Sales](https://car-sales-insight.vercel.app/) 和 [示例仓库](https://github.com/tidbcloud/car-sales-insight)。 - -## 开始之前 - -要完成本分步教程,你需要准备以下内容: - -- [Node.js](https://nodejs.org/en) >= 18.0.0。 -- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器。 -- 一个 TiDB Cloud Serverless 集群。如果你还没有,可以[创建一个 TiDB Cloud Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md)。 - -## 步骤 1. 创建本地 Node.js 项目 - -1. 创建一个名为 `node-example` 的项目: - - ```shell - mkdir node-example - cd node-example - ``` - -2. 使用 npm 或你喜欢的包管理器安装 TiDB Cloud serverless driver。 - - 以下命令以 npm 安装为例。执行该命令后,会在你的项目目录下创建 `node_modules` 目录和 `package.json` 文件。 - - ``` - npm install @tidbcloud/serverless - ``` - -## 步骤 2. 使用 serverless driver - -serverless driver 同时支持 CommonJS 和 ES modules。以下步骤以 ES module 的用法为例。 - -1. 在你的 TiDB Cloud Serverless 集群的概览页面,点击右上角的 **Connect**,然后在弹出的对话框中获取你的数据库连接字符串。连接字符串格式如下: - - ``` - mysql://[username]:[password]@[host]/[database] - ``` - -2. 在 `package.json` 文件中,通过添加 `type: "module"` 来指定 ES module。 - - 例如: - - ```json - { - "type": "module", - "dependencies": { - "@tidbcloud/serverless": "^0.0.7", - } - } - ``` - -3. 在你的项目目录下创建一个名为 `index.js` 的文件,并添加以下代码: - - ```js - import { connect } from '@tidbcloud/serverless' - - const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) // replace with your TiDB Cloud Serverless cluster information - console.log(await conn.execute("show tables")) - ``` - -4. 使用以下命令运行你的项目: - - ``` - node index.js - ``` - -## 与早期版本 Node.js 的兼容性 - -如果你使用的 Node.js 版本低于 18.0.0,不包含全局 `fetch` 函数,可以通过以下步骤获取 `fetch`: - -1. 安装一个提供 `fetch` 的包,例如 `undici`: - - ``` - npm install undici - ``` - -2. 将 `fetch` 函数传递给 `connect` 函数: - - ```js - import { connect } from '@tidbcloud/serverless' - import { fetch } from 'undici' - - const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]',fetch}) - ``` \ No newline at end of file diff --git a/tidb-cloud/serverless-driver-prisma-example.md b/tidb-cloud/serverless-driver-prisma-example.md deleted file mode 100644 index 4df5b29b279a1..0000000000000 --- a/tidb-cloud/serverless-driver-prisma-example.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -title: TiDB Cloud Serverless Driver Prisma 教程 -summary: 学习如何将 TiDB Cloud serverless driver 与 Prisma ORM 一起使用。 ---- - -# TiDB Cloud Serverless Driver Prisma 教程 - -[Prisma](https://www.prisma.io/docs) 是一个开源的下一代 ORM(对象关系映射),可以帮助开发者以直观、高效且安全的方式与数据库交互。TiDB Cloud 提供了 [@tidbcloud/prisma-adapter](https://github.com/tidbcloud/prisma-adapter),使你能够通过 HTTPS 使用 [Prisma Client](https://www.prisma.io/docs/concepts/components/prisma-client) 连接 [TiDB Cloud serverless driver](/tidb-cloud/serverless-driver.md)。与传统的 TCP 方式相比,[@tidbcloud/prisma-adapter](https://github.com/tidbcloud/prisma-adapter) 带来了以下优势: - -- 在 serverless 环境下提升 Prisma Client 的性能 -- 支持在 edge 环境下使用 Prisma Client - -本教程介绍如何在 serverless 环境和 edge 环境中使用 [@tidbcloud/prisma-adapter](https://github.com/tidbcloud/prisma-adapter)。 - -## 安装 - -你需要安装 [@tidbcloud/prisma-adapter](https://github.com/tidbcloud/prisma-adapter) 和 [TiDB Cloud serverless driver](/tidb-cloud/serverless-driver.md)。你可以使用 [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器进行安装。 - -以 npm 为例,你可以运行以下命令进行安装: - -```shell -npm install @tidbcloud/prisma-adapter -npm install @tidbcloud/serverless -``` - -## 启用 `driverAdapters` - -要使用 Prisma adapter,你需要在 `schema.prisma` 文件中启用 `driverAdapters` 特性。例如: - -```prisma -generator client { - provider = "prisma-client-js" - previewFeatures = ["driverAdapters"] -} - -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -## 初始化 Prisma Client - -在使用 Prisma Client 之前,你需要用 `@tidbcloud/prisma-adapter` 进行初始化。 - -对于 v6.6.0 之前的 `@tidbcloud/prisma-adapter`: - -```js -import { connect } from '@tidbcloud/serverless'; -import { PrismaTiDBCloud } from '@tidbcloud/prisma-adapter'; -import { PrismaClient } from '@prisma/client'; - -// Initialize Prisma Client -const connection = connect({ url: ${DATABASE_URL} }); -const adapter = new PrismaTiDBCloud(connection); -const prisma = new PrismaClient({ adapter }); -``` - -对于 v6.6.0 或更高版本的 `@tidbcloud/prisma-adapter`: - -```js -import { PrismaTiDBCloud } from '@tidbcloud/prisma-adapter'; -import { PrismaClient } from '@prisma/client'; - -// Initialize Prisma Client -const adapter = new PrismaTiDBCloud({ url: ${DATABASE_URL} }); -const prisma = new PrismaClient({ adapter }); -``` - -之后,Prisma Client 的查询将通过 TiDB Cloud serverless driver 进行处理。 - -## 在 Node.js 环境中使用 Prisma adapter - -本节提供了在 Node.js 环境下使用 `@tidbcloud/prisma-adapter` 的示例。 - -### 前置条件 - -完成本教程,你需要准备以下内容: - -- [Node.js](https://nodejs.org/en) >= 18.0.0 -- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 或你喜欢的包管理器 -- 一个 TiDB Cloud Serverless 集群。如果你还没有,可以[创建一个 TiDB Cloud Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md) - -### 步骤 1. 创建项目 - -1. 创建一个名为 `prisma-example` 的项目: - - ``` - mkdir prisma-example - cd prisma-example - ``` - -2. 安装 `@tidbcloud/prisma-adapter` 驱动适配器、`@tidbcloud/serverless` serverless driver 以及 Prisma CLI。 - - 以下命令以 npm 作为包管理器。执行 `npm install @tidbcloud/serverless` 会在你的项目目录下创建 `node_modules` 目录和 `package.json` 文件。 - - ``` - npm install @tidbcloud/prisma-adapter - npm install @tidbcloud/serverless - npm install prisma --save-dev - ``` - -3. 在 `package.json` 文件中,通过添加 `type: "module"` 指定 ES module: - - ```json - { - "type": "module", - "dependencies": { - "@prisma/client": "^6.6.0", - "@tidbcloud/prisma-adapter": "^6.6.0", - "@tidbcloud/serverless": "^0.1.0" - }, - "devDependencies": { - "prisma": "^6.6.0" - } - } - ``` - -### 步骤 2. 设置环境 - -1. 在 TiDB Cloud Serverless 集群的概览页面,点击右上角的 **Connect**,然后在弹出的对话框中获取你的数据库连接字符串。连接字符串格式如下: - - ``` - mysql://[username]:[password]@[host]:4000/[database]?sslaccept=strict - ``` - -2. 在项目根目录下创建一个名为 `.env` 的文件,定义名为 `DATABASE_URL` 的环境变量,并将该变量中的 `[]` 占位符替换为连接字符串中的对应参数。 - - ```dotenv - DATABASE_URL='mysql://[username]:[password]@[host]:4000/[database]?sslaccept=strict' - ``` - - > **Note:** - > - > `@tidbcloud/prisma-adapter` 仅支持通过 HTTPS 使用 Prisma Client。对于 [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate) 和 [Prisma Introspection](https://www.prisma.io/docs/concepts/components/introspection),仍然使用传统的 TCP 连接。如果你只需要使用 Prisma Client,可以将 `DATABASE_URL` 简化为 `mysql://[username]:[password]@[host]/[database]` 格式。 - -3. 安装 `dotenv` 以从 `.env` 文件加载环境变量: - - ``` - npm install dotenv - ``` - -### 步骤 3. 定义 schema - -1. 创建一个名为 `schema.prisma` 的文件。在该文件中,包含 `driverAdapters` 预览特性,并引用 `DATABASE_URL` 环境变量。示例文件如下: - - ``` - // schema.prisma - generator client { - provider = "prisma-client-js" - previewFeatures = ["driverAdapters"] - } - - datasource db { - provider = "mysql" - url = env("DATABASE_URL") - } - ``` - -2. 在 `schema.prisma` 文件中,为你的数据库表定义数据模型。以下示例定义了一个名为 `user` 的数据模型。 - - ``` - // schema.prisma - generator client { - provider = "prisma-client-js" - previewFeatures = ["driverAdapters"] - } - - datasource db { - provider = "mysql" - url = env("DATABASE_URL") - } - - // define a data model according to your database table - model user { - id Int @id @default(autoincrement()) - email String? @unique(map: "uniq_email") @db.VarChar(255) - name String? @db.VarChar(255) - } - ``` - -3. 使用 Prisma schema 同步你的数据库。你可以手动在 TiDB Cloud Serverless 集群中创建数据库表,也可以使用 Prisma CLI 自动创建: - - ``` - npx prisma db push - ``` - - 该命令会通过传统的 TCP 连接在 TiDB Cloud Serverless 集群中创建 `user` 表,而不是通过 `@tidbcloud/prisma-adapter` 的 HTTPS 连接。这是因为它使用了与 Prisma Migrate 相同的引擎。关于该命令的更多信息,请参见 [Prototype your schema](https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push)。 - -4. 生成 Prisma Client: - - ``` - npx prisma generate - ``` - - 该命令会根据 Prisma schema 生成 Prisma Client。 - -### 步骤 4. 执行 CRUD 操作 - -1. 创建一个名为 `hello-word.js` 的文件,并添加以下代码以初始化 Prisma Client: - - ```js - import { PrismaTiDBCloud } from '@tidbcloud/prisma-adapter'; - import { PrismaClient } from '@prisma/client'; - import dotenv from 'dotenv'; - - // setup - dotenv.config(); - const connectionString = `${process.env.DATABASE_URL}`; - - // Initialize Prisma Client - const adapter = new PrismaTiDBCloud({ url: connectionString }); - const prisma = new PrismaClient({ adapter }); - ``` - -2. 使用 Prisma Client 执行一些 CRUD 操作。例如: - - ```js - // Insert - const user = await prisma.user.create({ - data: { - email: 'test@pingcap.com', - name: 'test', - }, - }) - console.log(user) - - // Query - console.log(await prisma.user.findMany()) - - // Delete - await prisma.user.delete({ - where: { - id: user.id, - }, - }) - ``` - -3. 使用 Prisma Client 执行一些事务操作。例如: - - ```js - const createUser1 = prisma.user.create({ - data: { - email: 'test1@pingcap.com', - name: 'test1', - }, - }) - const createUser2 = prisma.user.create({ - data: { - email: 'test1@pingcap.com', - name: 'test1', - }, - }) - const createUser3 = prisma.user.create({ - data: { - email: 'test2@pingcap.com', - name: 'test2', - }, - }) - - try { - await prisma.$transaction([createUser1, createUser2]) // Operations fail because the email address is duplicated - } catch (e) { - console.log(e) - } - - try { - await prisma.$transaction([createUser2, createUser3]) // Operations success because the email address is unique - } catch (e) { - console.log(e) - } - ``` - -## 在 edge 环境中使用 Prisma adapter - -你可以在 edge 环境(如 Vercel Edge Functions 和 Cloudflare Workers)中使用 v5.11.0 或更高版本的 `@tidbcloud/prisma-adapter`。 - -- [Vercel Edge Function 示例](https://github.com/tidbcloud/serverless-driver-example/tree/main/prisma/prisma-vercel-example) -- [Cloudflare Workers 示例](https://github.com/tidbcloud/serverless-driver-example/tree/main/prisma/prisma-cloudflare-worker-example) diff --git a/tidb-cloud/serverless-driver.md b/tidb-cloud/serverless-driver.md deleted file mode 100644 index 43627abda1fc9..0000000000000 --- a/tidb-cloud/serverless-driver.md +++ /dev/null @@ -1,350 +0,0 @@ ---- -title: TiDB Cloud Serverless Driver (Beta) -summary: 了解如何从 serverless 和 edge 环境连接到 TiDB Cloud Starter 或 TiDB Cloud Essential。 -aliases: ['/tidbcloud/serverless-driver-config'] ---- - -# TiDB Cloud Serverless Driver (Beta) - -> **注意:** -> -> serverless driver 目前为 beta 版本,仅适用于 TiDB Cloud Starter 或 TiDB Cloud Essential 集群。 - -## 为什么要使用 TiDB Cloud Serverless Driver (Beta) - -传统的基于 TCP 的 MySQL driver 并不适用于 serverless 函数,因为它们期望建立长连接、持久的 TCP 连接,而这与 serverless 函数的短生命周期特性相矛盾。此外,在 [Vercel Edge Functions](https://vercel.com/docs/functions/edge-functions) 和 [Cloudflare Workers](https://workers.cloudflare.com/) 等 edge 环境中,可能缺乏对完整 TCP 支持和完整 Node.js 兼容性,这些 driver 可能根本无法工作。 - -[TiDB Cloud serverless driver (Beta)](https://github.com/tidbcloud/serverless-js) 针对 JavaScript,可以让你通过 HTTP 连接到 TiDB Cloud Starter 或 TiDB Cloud Essential 集群,而 HTTP 通常被 serverless 环境所支持。借助该 driver,你可以从 edge 环境连接到 TiDB Cloud Starter 或 TiDB Cloud Essential 集群,并减少 TCP 带来的连接开销,同时保持与传统基于 TCP 的 MySQL driver 类似的开发体验。 - -> **注意:** -> -> 如果你更喜欢使用 RESTful API 进行编程而不是 SQL 或 ORM,可以使用 [Data Service (beta)](/tidb-cloud/data-service-overview.md)。 - -## 安装 serverless driver - -你可以通过 npm 安装该 driver: - -```bash -npm install @tidbcloud/serverless -``` - -## 使用 serverless driver - -你可以使用 serverless driver 查询 TiDB Cloud Starter 或 TiDB Cloud Essential 集群中的数据,或执行交互式事务。 - -### 查询 - -要从 TiDB Cloud Starter 或 TiDB Cloud Essential 集群查询数据,你需要先创建连接。然后可以使用该连接执行原生 SQL 查询。例如: - -```ts -import { connect } from '@tidbcloud/serverless' - -const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) -const results = await conn.execute('select * from test where id = ?',[1]) -``` - -### 事务(实验性) - -你也可以使用 serverless driver 执行交互式事务。例如: - -```ts -import { connect } from '@tidbcloud/serverless' - -const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) -const tx = await conn.begin() - -try { - await tx.execute('insert into test values (1)') - await tx.execute('select * from test') - await tx.commit() -} catch (err) { - await tx.rollback() - throw err -} -``` - -## Edge 环境示例 - -以下是在 edge 环境中使用 serverless driver 的一些示例。你也可以尝试这个完整的 [在线演示](https://github.com/tidbcloud/car-sales-insight)。 - - - -
- -```ts -import { NextResponse } from 'next/server'; -import type { NextRequest } from 'next/server'; -import { connect } from '@tidbcloud/serverless' -export const runtime = 'edge' - -export async function GET(request: NextRequest) { - const conn = connect({url: process.env.DATABASE_URL}) - const result = await conn.execute('show tables') - return NextResponse.json({result}); -} -``` - -了解更多关于 [在 Vercel 中使用 TiDB Cloud serverless driver](/tidb-cloud/integrate-tidbcloud-with-vercel.md)。 - -
- -
- -```ts -import { connect } from '@tidbcloud/serverless' -export interface Env { - DATABASE_URL: string; -} -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { - const conn = connect({url: env.DATABASE_URL}) - const result = await conn.execute('show tables') - return new Response(JSON.stringify(result)); - }, -}; -``` - -了解更多关于 [在 Cloudflare Workers 中使用 TiDB Cloud serverless driver](/tidb-cloud/integrate-tidbcloud-with-cloudflare.md)。 - -
- -
- -```ts -import { connect } from 'https://esm.sh/@tidbcloud/serverless' - -export default async () => { - const conn = connect({url: Netlify.env.get('DATABASE_URL')}) - const result = await conn.execute('show tables') - return new Response(JSON.stringify(result)); -} -``` - -了解更多关于 [在 Netlify 中使用 TiDB Cloud serverless driver](/tidb-cloud/integrate-tidbcloud-with-netlify.md#use-the-edge-function)。 - -
- -
- -```ts -import { connect } from "npm:@tidbcloud/serverless" - -const conn = connect({url: Deno.env.get('DATABASE_URL')}) -const result = await conn.execute('show tables') -``` - -
- -
- -```ts -import { connect } from "@tidbcloud/serverless" - -const conn = connect({url: Bun.env.DATABASE_URL}) -const result = await conn.execute('show tables') -``` - -
- -
- -## 配置 serverless driver - -你可以在连接级别和 SQL 级别配置 TiDB Cloud serverless driver。 - -### 连接级别配置 - -在连接级别,你可以进行如下配置: - -| 名称 | 类型 | 默认值 | 描述 | -|--------------|----------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `username` | string | N/A | 集群的用户名。 | -| `password` | string | N/A | 集群的密码。 | -| `host` | string | N/A | 集群的主机名。 | -| `database` | string | `test` | 集群的数据库。 | -| `url` | string | N/A | 数据库的 URL,格式为 `mysql://[username]:[password]@[host]/[database]`,其中 `database` 可省略(如果你打算连接到默认数据库)。 | -| `fetch` | function | global fetch | 自定义 fetch 函数。例如,你可以在 node.js 中使用 `undici` 的 fetch。 | -| `arrayMode` | bool | `false` | 是否以数组而非对象的形式返回结果。为了获得更好的性能,可以设置为 `true`。 | -| `fullResult` | bool | `false` | 是否返回完整结果对象而不仅仅是行数据。为了获得更详细的结果,可以设置为 `true`。 | -| `decoders` | object | `{}` | 一组键值对,允许你自定义不同列类型的解码过程。在每个键值对中,你可以指定列类型作为 key,并指定相应的函数作为 value。该函数以 TiDB Cloud serverless driver 返回的原始字符串值为参数,并返回解码后的值。 | - -**数据库 URL** - -> **注意:** -> -> 如果你的用户名、密码或数据库名包含特殊字符,在通过 URL 传递时必须对这些字符进行 [百分号编码](https://en.wikipedia.org/wiki/Percent-encoding)。例如,密码 `password1@//?` 需要在 URL 中编码为 `password1%40%2F%2F%3F`。 - -当配置了 `url` 后,无需单独配置 `host`、`username`、`password` 和 `database`。以下代码是等价的: - -```ts -const config = { - host: '', - username: '', - password: '', - database: '', - arrayMode: true, -} - -const conn = connect(config) -``` - -```ts -const config = { - url: process.env['DATABASE_URL'] || 'mysql://[username]:[password]@[host]/[database]', - arrayMode: true -} - -const conn = connect(config) -``` - -### SQL 级别选项 - -> **注意:** -> -> SQL 级别选项的优先级高于连接级别配置。 - -在 SQL 级别,你可以配置如下选项: - -| 选项 | 类型 | 默认值 | 描述 | -|--------------|--------|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `arrayMode` | bool | `false` | 是否以数组而非对象的形式返回结果。为了获得更好的性能,可以设置为 `true`。 | -| `fullResult` | bool | `false` | 是否返回完整结果对象而不仅仅是行数据。为了获得更详细的结果,可以设置为 `true`。 | -| `isolation` | string | `REPEATABLE READ`| 事务隔离级别,可设置为 `READ COMMITTED` 或 `REPEATABLE READ`。 | -| `decoders` | object | `{}` | 一组键值对,允许你自定义不同列类型的解码过程。在每个键值对中,你可以指定列类型作为 key,并指定相应的函数作为 value。该函数以 TiDB Cloud serverless driver 返回的原始字符串值为参数,并返回解码后的值。如果你在连接级别和 SQL 级别都配置了 `decoders`,则连接级别中 key 不同的键值对会合并到 SQL 级别生效;如果同一个 key(即列类型)在两级都指定,则以 SQL 级别为准。 | - -**arrayMode 和 fullResult** - -如果你希望以数组形式返回完整结果对象,可以如下配置 `arrayMode` 和 `fullResult` 选项: - -```ts -const conn = connect({url: process.env['DATABASE_URL'] || 'mysql://[username]:[password]@[host]/[database]'}) -const results = await conn.execute('select * from test',null,{arrayMode:true,fullResult:true}) -``` - -**isolation** - -`isolation` 选项只能在 `begin` 方法中使用。 - -```ts -const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) -const tx = await conn.begin({isolation:"READ COMMITTED"}) -``` - -**decoders** - -如果你想自定义返回列值的格式,可以在 `connect()` 方法中配置 `decoder` 选项,如下所示: - -```ts -import { connect, ColumnType } from '@tidbcloud/serverless'; - -const conn = connect({ - url: 'mysql://[username]:[password]@[host]/[database]', - decoders: { - // 默认情况下,TiDB Cloud serverless driver 会将 BIGINT 类型作为文本值返回。此 decoder 将 BIGINT 转换为 JavaScript 内置的 BigInt 类型。 - [ColumnType.BIGINT]: (rawValue: string) => BigInt(rawValue), - - // 默认情况下,TiDB Cloud serverless driver 会将 DATETIME 类型以 'yyyy-MM-dd HH:mm:ss' 格式的文本值返回。此 decoder 将 DATETIME 文本转换为 JavaScript 原生 Date 对象。 - [ColumnType.DATETIME]: (rawValue: string) => new Date(rawValue), - } -}) - -// 你也可以在 SQL 级别配置 decoder 选项,以覆盖连接级别相同 key 的 decoders。 -conn.execute(`select ...`, [], { - decoders: { - // ... - } -}) -``` - -> **注意:** -> -> TiDB Cloud serverless driver 配置变更: -> -> - v0.0.7:新增 SQL 级别选项 `isolation`。 -> - v0.0.10:新增连接级别配置 `decoders` 和 SQL 级别选项 `decoders`。 - -## 功能特性 - -### 支持的 SQL 语句 - -支持 DDL,支持以下 SQL 语句:`SELECT`、`SHOW`、`EXPLAIN`、`USE`、`INSERT`、`UPDATE`、`DELETE`、`BEGIN`、`COMMIT`、`ROLLBACK` 和 `SET`。 - -### 数据类型映射 - -TiDB 与 Javascript 之间的类型映射如下: - -| TiDB 数据类型 | Javascript 类型 | -|----------------------|-----------------| -| TINYINT | number | -| UNSIGNED TINYINT | number | -| BOOL | number | -| SMALLINT | number | -| UNSIGNED SMALLINT | number | -| MEDIUMINT | number | -| INT | number | -| UNSIGNED INT | number | -| YEAR | number | -| FLOAT | number | -| DOUBLE | number | -| BIGINT | string | -| UNSIGNED BIGINT | string | -| DECIMAL | string | -| CHAR | string | -| VARCHAR | string | -| BINARY | Uint8Array | -| VARBINARY | Uint8Array | -| TINYTEXT | string | -| TEXT | string | -| MEDIUMTEXT | string | -| LONGTEXT | string | -| TINYBLOB | Uint8Array | -| BLOB | Uint8Array | -| MEDIUMBLOB | Uint8Array | -| LONGBLOB | Uint8Array | -| DATE | string | -| TIME | string | -| DATETIME | string | -| TIMESTAMP | string | -| ENUM | string | -| SET | string | -| BIT | Uint8Array | -| JSON | object | -| NULL | null | -| Others | string | - -> **注意:** -> -> 请确保在 TiDB Cloud 中使用默认的 `utf8mb4` 字符集进行类型转换为 JavaScript 字符串,因为 TiDB Cloud serverless driver 使用 UTF-8 编码将其解码为字符串。 - -> **注意:** -> -> TiDB Cloud serverless driver 数据类型映射变更: -> -> - v0.1.0:`BINARY`、`VARBINARY`、`TINYBLOB`、`BLOB`、`MEDIUMBLOB`、`LONGBLOB` 和 `BIT` 类型现在返回为 `Uint8Array`,而不是 `string`。 - -### ORM 集成 - -TiDB Cloud serverless driver 已集成以下 ORM: - -- [TiDB Cloud serverless driver Kysely dialect](https://github.com/tidbcloud/kysely)。 -- [TiDB Cloud serverless driver Prisma adapter](https://github.com/tidbcloud/prisma-adapter)。 - -## 计费 - -serverless driver 本身免费,但使用该 driver 访问数据会产生 [Request Units (RUs)](/tidb-cloud/tidb-cloud-glossary.md#request-unit-ru) 和存储用量。 - -- 对于 TiDB Cloud Starter 集群,计费遵循 [TiDB Cloud Starter 计费](https://www.pingcap.com/tidb-cloud-starter-pricing-details/) 模型。 -- 对于 TiDB Cloud Essential 集群,计费遵循 [TiDB Cloud Essential 计费](https://www.pingcap.com/tidb-cloud-essential-pricing-details/) 模型。 - -## 限制 - -目前,使用 serverless driver 有如下限制: - -- 单次查询最多可获取 10,000 行数据。 -- 每次只能执行一条 SQL 语句,不支持在一个查询中执行多条 SQL 语句。 -- 暂不支持通过 [私有端点](/tidb-cloud/set-up-private-endpoint-connections-serverless.md) 连接。 -- 为保护你的凭证,服务端会通过跨域资源共享(CORS)阻止来自未授权浏览器来源的请求。因此,你只能在后端服务中使用 serverless driver。 - -## 后续步骤 - -- 了解如何 [在本地 Node.js 项目中使用 TiDB Cloud serverless driver](/tidb-cloud/serverless-driver-node-example.md)。 \ No newline at end of file diff --git a/tidb-cloud/vector-search-auto-embedding-amazon-titan.md b/tidb-cloud/vector-search-auto-embedding-amazon-titan.md deleted file mode 100644 index 4f273d4be1d47..0000000000000 --- a/tidb-cloud/vector-search-auto-embedding-amazon-titan.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: Amazon Titan Embeddings -summary: 了解如何在 TiDB Cloud 中使用 Amazon Titan 嵌入模型。 ---- - -# Amazon Titan Embeddings - -本文档介绍如何在 TiDB Cloud 中结合 [Auto Embedding](/tidb-cloud/vector-search-auto-embedding-overview.md) 使用 Amazon Titan 嵌入模型,从文本查询中执行语义搜索。 - -> **Note:** -> -> [Auto Embedding](/tidb-cloud/vector-search-auto-embedding-overview.md) 仅适用于托管在 AWS 上的 TiDB Cloud Starter 集群。 - -## 可用模型 - -TiDB Cloud 原生提供以下 [Amazon Titan 嵌入模型](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html)。无需 API 密钥。 - -**Amazon Titan Text Embedding V2 模型** - -- 名称:`tidbcloud_free/amazon/titan-embed-text-v2` -- 维度:1024(默认)、512、256 -- 距离度量:Cosine、L2 -- 支持语言:英语(预览支持 100+ 种语言) -- 典型用例:RAG、文档检索、重排序、分类 -- 最大输入文本 token 数:8,192 -- 最大输入文本字符数:50,000 -- 价格:免费 -- 由 TiDB Cloud 托管:✅ -- 支持自带密钥:❌ - -关于该模型的更多信息,请参见 [Amazon Bedrock 文档](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html)。 - -## SQL 使用示例 - -以下示例展示了如何结合 Auto Embedding 使用 Amazon Titan 嵌入模型。 - -```sql -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "tidbcloud_free/amazon/titan-embed-text-v2", - `content` - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -结果: - -``` -+------+----------------------------------------------------------------+ -| id | content | -+------+----------------------------------------------------------------+ -| 1 | Java: Object-oriented language for cross-platform development. | -| 4 | Java's syntax is used in Android apps. | -+------+----------------------------------------------------------------+ -``` - -## 可选参数 - -你可以通过 `EMBED_TEXT()` 函数的 `additional_json_options` 参数指定以下选项: - -- `normalize`(可选):是否对输出嵌入向量进行归一化。默认为 `true`。 -- `dimensions`(可选):输出嵌入向量的维度。支持的取值:`1024`(默认)、`512`、`256`。 - -**示例:使用其他维度** - -```sql -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(512) GENERATED ALWAYS AS (EMBED_TEXT( - "tidbcloud_free/amazon/titan-embed-text-v2", - `content`, - '{"dimensions": 512}' - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -结果: - -``` -+------+----------------------------------------------------------------+ -| id | content | -+------+----------------------------------------------------------------+ -| 1 | Java: Object-oriented language for cross-platform development. | -| 4 | Java's syntax is used in Android apps. | -+------+----------------------------------------------------------------+ -``` - -## Python 使用示例 - -参见 [PyTiDB 文档](https://pingcap.github.io/ai/guides/auto-embedding/)。 - -## 参见 - -- [Auto Embedding 概览](/tidb-cloud/vector-search-auto-embedding-overview.md) -- [向量检索](/vector-search/vector-search-overview.md) -- [向量函数与操作符](/vector-search/vector-search-functions-and-operators.md) -- [混合检索](/tidb-cloud/vector-search-hybrid-search.md) diff --git a/tidb-cloud/vector-search-auto-embedding-cohere.md b/tidb-cloud/vector-search-auto-embedding-cohere.md deleted file mode 100644 index 46ae87452adc0..0000000000000 --- a/tidb-cloud/vector-search-auto-embedding-cohere.md +++ /dev/null @@ -1,212 +0,0 @@ ---- -title: Cohere Embeddings -summary: 了解如何在 TiDB Cloud 中使用 Cohere 嵌入模型。 ---- - -# Cohere Embeddings - -本文档介绍如何在 TiDB Cloud 中结合 [Auto Embedding](/tidb-cloud/vector-search-auto-embedding-overview.md) 使用 Cohere 嵌入模型,从文本查询中执行语义搜索。 - -> **Note:** -> -> [Auto Embedding](/tidb-cloud/vector-search-auto-embedding-overview.md) 仅在托管于 AWS 的 TiDB Cloud Starter 集群上可用。 - -## 可用模型 - -TiDB Cloud 原生提供以下 [Cohere](https://cohere.com/) 嵌入模型。无需 API 密钥。 - -**Cohere Embed v3 model** - -- 名称:`tidbcloud_free/cohere/embed-english-v3` -- 维度:1024 -- 距离度量:Cosine,L2 -- 语言:英语 -- 最大输入文本 token 数:512(约每个 token 4 个字符) -- 最大输入文本字符数:2,048 -- 价格:免费 -- 由 TiDB Cloud 托管:✅ `tidbcloud_free/cohere/embed-english-v3` -- 自带密钥:✅ `cohere/embed-english-v3.0` - -**Cohere Multilingual Embed v3 model** - -- 名称:`tidbcloud_free/cohere/embed-multilingual-v3` -- 维度:1024 -- 距离度量:Cosine,L2 -- 语言:100+ 种语言 -- 最大输入文本 token 数:512(约每个 token 4 个字符) -- 最大输入文本字符数:2,048 -- 价格:免费 -- 由 TiDB Cloud 托管:✅ `tidbcloud_free/cohere/embed-multilingual-v3` -- 自带密钥:✅ `cohere/embed-multilingual-v3.0` - -另外,如果你自带 Cohere API 密钥(BYOK),所有 Cohere 模型均可通过 `cohere/` 前缀使用。例如: - -**Cohere Embed v4 model** - -- 名称:`cohere/embed-v4.0` -- 维度:256、512、1024、1536(默认) -- 距离度量:Cosine,L2 -- 最大输入文本 token 数:128,000 -- 价格:由 Cohere 收费 -- 由 TiDB Cloud 托管:❌ -- 自带密钥:✅ - -完整的 Cohere 模型列表请参见 [Cohere Documentation](https://docs.cohere.com/docs/cohere-embed)。 - -## SQL 使用示例(TiDB Cloud 托管) - -以下示例展示了如何结合 Auto Embedding 使用 TiDB Cloud 托管的 Cohere 嵌入模型。 - -```sql -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "tidbcloud_free/cohere/embed-multilingual-v3", - `content`, - '{"input_type": "search_document", "input_type@search": "search_query"}' - )) STORED -); -``` - -> **Note:** -> -> - 对于 Cohere 嵌入模型,你必须在定义表时于 `EMBED_TEXT()` 函数中指定 `input_type`。例如,`'{"input_type": "search_document", "input_type@search": "search_query"}'` 表示插入数据时 `input_type` 设为 `search_document`,向量搜索时自动应用 `search_query`。 -> - `@search` 后缀表示该字段仅在向量搜索查询时生效,因此在查询时无需再次指定 `input_type`。 - -插入和查询数据: - -```sql -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -结果: - -``` -+------+----------------------------------------------------------------+ -| id | content | -+------+----------------------------------------------------------------+ -| 1 | Java: Object-oriented language for cross-platform development. | -| 4 | Java's syntax is used in Android apps. | -+------+----------------------------------------------------------------+ -``` - -## 选项(TiDB Cloud 托管) - -**Embed v3** 和 **Multilingual Embed v3** 模型均支持以下选项,你可以通过 `EMBED_TEXT()` 函数的 `additional_json_options` 参数进行指定。 - -- `input_type`(必填):在嵌入前添加特殊 token 以指示嵌入用途。你在为同一任务生成嵌入时必须始终使用相同的 input type,否则嵌入会被映射到不同的语义空间,导致不兼容。唯一的例外是语义搜索,文档使用 `search_document`,查询使用 `search_query`。 - - - `search_document`:从文档生成嵌入,用于存储到向量数据库。 - - `search_query`:从查询生成嵌入,用于在向量数据库中检索已存储的嵌入。 - - `classification`:生成嵌入,作为文本分类器的输入。 - - `clustering`:生成嵌入,用于聚类任务。 - -- `truncate`(可选):控制 API 如何处理超出最大 token 长度的输入。可选值如下: - - - `NONE`(默认):当输入超过最大 token 长度时返回错误。 - - `START`:从开头截断文本,直到输入符合要求。 - - `END`:从结尾截断文本,直到输入符合要求。 - -## SQL 使用示例(BYOK) - -如需使用自带密钥(BYOK)的 Cohere 模型,你必须按如下方式指定 Cohere API 密钥: - -> **Note** -> -> 请将 `'your-cohere-api-key-here'` 替换为你的实际 Cohere API 密钥。你可以在 [Cohere Dashboard](https://dashboard.cohere.com/) 获取 API 密钥。 - -```sql -SET @@GLOBAL.TIDB_EXP_EMBED_COHERE_API_KEY = 'your-cohere-api-key-here'; - -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "cohere/embed-v4.0", - `content`, - '{"input_type": "search_document", "input_type@search": "search_query"}' - )) STORED -); - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -## 选项(BYOK) - -所有 [Cohere 嵌入选项](https://docs.cohere.com/v2/reference/embed) 均可通过 `EMBED_TEXT()` 函数的 `additional_json_options` 参数进行设置。 - -**示例:为搜索和插入操作分别指定不同的 `input_type`** - -使用 `@search` 后缀表示该字段仅在向量搜索查询时生效。 - -```sql -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "cohere/embed-v4.0", - `content`, - '{"input_type": "search_document", "input_type@search": "search_query"}' - )) STORED -); -``` - -**示例:使用不同的维度** - -```sql -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(512) GENERATED ALWAYS AS (EMBED_TEXT( - "cohere/embed-v4.0", - `content`, - '{"output_dimension": 512}' - )) STORED -); -``` - -所有可用选项请参见 [Cohere Documentation](https://docs.cohere.com/v2/reference/embed)。 - -## Python 使用示例 - -参见 [PyTiDB Documentation](https://pingcap.github.io/ai/guides/auto-embedding/)。 - -## 参见 - -- [Auto Embedding Overview](/tidb-cloud/vector-search-auto-embedding-overview.md) -- [Vector Search](/vector-search/vector-search-overview.md) -- [Vector Functions and Operators](/vector-search/vector-search-functions-and-operators.md) -- [Hybrid Search](/tidb-cloud/vector-search-hybrid-search.md) diff --git a/tidb-cloud/vector-search-auto-embedding-huggingface.md b/tidb-cloud/vector-search-auto-embedding-huggingface.md deleted file mode 100644 index f7ebce6d1ab95..0000000000000 --- a/tidb-cloud/vector-search-auto-embedding-huggingface.md +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: HuggingFace Embeddings -summary: 了解如何在 TiDB Cloud 中使用 HuggingFace 嵌入模型。 ---- - -# HuggingFace Embeddings - -本文档介绍如何在 TiDB Cloud 中结合 [Auto Embedding](/tidb-cloud/vector-search-auto-embedding-overview.md) 使用 HuggingFace 嵌入模型,从文本查询中执行语义搜索。 - -> **Note:** -> -> [Auto Embedding](/tidb-cloud/vector-search-auto-embedding-overview.md) 仅在托管于 AWS 的 TiDB Cloud Starter 集群上可用。 - -## 可用模型 - -如果你自带 [HuggingFace Inference API](https://huggingface.co/docs/inference-providers/index) 密钥(BYOK),则可以通过 `huggingface/` 前缀使用 HuggingFace 模型。 - -为方便起见,以下章节以几个流行模型为例,展示如何结合 Auto Embedding 使用它们。完整可用模型列表请参见 [HuggingFace Models](https://huggingface.co/models?library=sentence-transformers&inference_provider=hf-inference&sort=trending)。请注意,并非所有模型都由 HuggingFace Inference API 提供,或始终可用。 - -## multilingual-e5-large - -- 名称: `huggingface/intfloat/multilingual-e5-large` -- 维度: 1024 -- 距离度量: Cosine, L2 -- 价格: 由 HuggingFace 收费 -- TiDB Cloud 托管: ❌ -- 支持自带密钥: ✅ -- 项目主页: - -示例: - -```sql -SET @@GLOBAL.TIDB_EXP_EMBED_HUGGINGFACE_API_KEY = 'your-huggingface-api-key-here'; - -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "huggingface/intfloat/multilingual-e5-large", - `content` - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -## bge-m3 - -- 名称: `huggingface/BAAI/bge-m3` -- 维度: 1024 -- 距离度量: Cosine, L2 -- 价格: 由 HuggingFace 收费 -- TiDB Cloud 托管: ❌ -- 支持自带密钥: ✅ -- 项目主页: - -```sql -SET @@GLOBAL.TIDB_EXP_EMBED_HUGGINGFACE_API_KEY = 'your-huggingface-api-key-here'; - -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "huggingface/BAAI/bge-m3", - `content` - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -## all-MiniLM-L6-v2 - -- 名称: `huggingface/sentence-transformers/all-MiniLM-L6-v2` -- 维度: 384 -- 距离度量: Cosine, L2 -- 价格: 由 HuggingFace 收费 -- TiDB Cloud 托管: ❌ -- 支持自带密钥: ✅ -- 项目主页: - -示例: - -```sql -SET @@GLOBAL.TIDB_EXP_EMBED_HUGGINGFACE_API_KEY = 'your-huggingface-api-key-here'; - -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(384) GENERATED ALWAYS AS (EMBED_TEXT( - "huggingface/sentence-transformers/all-MiniLM-L6-v2", - `content` - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -## all-mpnet-base-v2 - -- 名称: `huggingface/sentence-transformers/all-mpnet-base-v2` -- 维度: 768 -- 距离度量: Cosine, L2 -- 价格: 由 HuggingFace 收费 -- TiDB Cloud 托管: ❌ -- 支持自带密钥: ✅ -- 项目主页: - -```sql -SET @@GLOBAL.TIDB_EXP_EMBED_HUGGINGFACE_API_KEY = 'your-huggingface-api-key-here'; - -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(768) GENERATED ALWAYS AS (EMBED_TEXT( - "huggingface/sentence-transformers/all-mpnet-base-v2", - `content` - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -## Qwen3-Embedding-0.6B - -> **Note:** -> -> HuggingFace Inference API 对该模型可能不稳定。 - -- 名称: `huggingface/Qwen/Qwen3-Embedding-0.6B` -- 维度: 1024 -- 距离度量: Cosine, L2 -- 最大输入文本 tokens 数: 512 -- 价格: 由 HuggingFace 收费 -- TiDB Cloud 托管: ❌ -- 支持自带密钥: ✅ -- 项目主页: - -```sql -SET @@GLOBAL.TIDB_EXP_EMBED_HUGGINGFACE_API_KEY = 'your-huggingface-api-key-here'; - -CREATE TABLE sample ( - `id` INT, - `content` TEXT, - `embedding` VECTOR(1024) GENERATED ALWAYS AS (EMBED_TEXT( - "huggingface/Qwen/Qwen3-Embedding-0.6B", - `content` - )) STORED -); - - -INSERT INTO sample - (`id`, `content`) -VALUES - (1, "Java: Object-oriented language for cross-platform development."), - (2, "Java coffee: Bold Indonesian beans with low acidity."), - (3, "Java island: Densely populated, home to Jakarta."), - (4, "Java's syntax is used in Android apps."), - (5, "Dark roast Java beans enhance espresso blends."); - - -SELECT `id`, `content` FROM sample -ORDER BY - VEC_EMBED_COSINE_DISTANCE( - embedding, - "How to start learning Java programming?" - ) -LIMIT 2; -``` - -## Python 使用示例 - -参见 [PyTiDB Documentation](https://pingcap.github.io/ai/guides/auto-embedding/)。 - -## 参见 - -- [Auto Embedding 概览](/tidb-cloud/vector-search-auto-embedding-overview.md) -- [向量检索](/vector-search/vector-search-overview.md) -- [向量函数与操作符](/vector-search/vector-search-functions-and-operators.md) -- [混合检索](/tidb-cloud/vector-search-hybrid-search.md) diff --git a/tidb-cloud/vector-search-auto-embedding-overview.md b/tidb-cloud/vector-search-auto-embedding-overview.md deleted file mode 100644 index 691f45d2c1e6f..0000000000000 --- a/tidb-cloud/vector-search-auto-embedding-overview.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -title: Auto Embedding 概述 -summary: 了解如何使用 Auto Embedding 通过纯文本而非向量进行语义搜索。 ---- - -# Auto Embedding 概述 - -Auto Embedding 功能允许你直接使用纯文本进行向量搜索,无需自行提供向量。通过该功能,你可以直接插入文本数据,并使用文本查询进行语义搜索,TiDB 会在后台自动将文本转换为向量。 - -要使用 Auto Embedding,基本流程如下: - -1. **定义一张表**,包含一个文本列和一个使用 `EMBED_TEXT()` 生成的向量列。 -2. **插入文本数据** —— 向量会自动生成并同时存储。 -3. **使用文本进行查询** —— 使用 `VEC_EMBED_COSINE_DISTANCE()` 或 `VEC_EMBED_L2_DISTANCE()` 查找语义相似的内容。 - -> **注意:** -> -> Auto Embedding 仅在托管于 AWS 的 TiDB Cloud Starter 集群上可用。 - -## 快速入门示例 - -> **提示:** -> -> 有关 Python 的用法,请参见 [PyTiDB 文档](https://pingcap.github.io/ai/guides/auto-embedding/)。 - -以下示例展示了如何使用 Auto Embedding 结合余弦距离进行语义搜索。此示例无需 API key。 - -```sql --- Create a table with auto-embedding --- The dimension of the vector column must match the dimension of the embedding model, --- otherwise TiDB returns an error when inserting data. -CREATE TABLE documents ( - id INT PRIMARY KEY AUTO_INCREMENT, - content TEXT, - content_vector VECTOR(1024) GENERATED ALWAYS AS ( - EMBED_TEXT("tidbcloud_free/amazon/titan-embed-text-v2", content) - ) STORED -); - --- Insert text data (vectors are generated automatically) -INSERT INTO documents (content) VALUES - ("Electric vehicles reduce air pollution in cities."), - ("Solar panels convert sunlight into renewable energy."), - ("Plant-based diets lower carbon footprints significantly."), - ("Deep learning algorithms improve medical diagnosis accuracy."), - ("Blockchain technology enhances data security systems."); - --- Search for semantically similar content using text query -SELECT id, content FROM documents -ORDER BY VEC_EMBED_COSINE_DISTANCE( - content_vector, - "Renewable energy solutions for environmental protection" -) -LIMIT 3; -``` - -输出如下: - -``` -+----+--------------------------------------------------------------+ -| id | content | -+----+--------------------------------------------------------------+ -| 2 | Solar panels convert sunlight into renewable energy. | -| 1 | Electric vehicles reduce air pollution in cities. | -| 4 | Deep learning algorithms improve medical diagnosis accuracy. | -+----+--------------------------------------------------------------+ -``` - -上述示例使用了 Amazon Titan 模型。关于其他模型,请参见 [可用的文本嵌入模型](#available-text-embedding-models)。 - -## Auto Embedding + 向量索引 - -Auto Embedding 可与 [向量索引](/vector-search/vector-search-index.md) 配合使用,以提升查询性能。你可以在生成的向量列上定义向量索引,系统会自动使用该索引: - -```sql --- Create a table with auto-embedding and a vector index -CREATE TABLE documents ( - id INT PRIMARY KEY AUTO_INCREMENT, - content TEXT, - content_vector VECTOR(1024) GENERATED ALWAYS AS ( - EMBED_TEXT("tidbcloud_free/amazon/titan-embed-text-v2", content) - ) STORED, - VECTOR INDEX ((VEC_COSINE_DISTANCE(content_vector))) -); - --- Insert text data (vectors are generated automatically) -INSERT INTO documents (content) VALUES - ("Electric vehicles reduce air pollution in cities."), - ("Solar panels convert sunlight into renewable energy."), - ("Plant-based diets lower carbon footprints significantly."), - ("Deep learning algorithms improve medical diagnosis accuracy."), - ("Blockchain technology enhances data security systems."); - --- Search for semantically similar content with a text query on the vector index using the same VEC_EMBED_COSINE_DISTANCE() function -SELECT id, content FROM documents -ORDER BY VEC_EMBED_COSINE_DISTANCE( - content_vector, - "Renewable energy solutions for environmental protection" -) -LIMIT 3; -``` - -> **注意:** -> -> - 定义向量索引时,使用 `VEC_COSINE_DISTANCE()` 或 `VEC_L2_DISTANCE()`。 -> - 查询时,使用 `VEC_EMBED_COSINE_DISTANCE()` 或 `VEC_EMBED_L2_DISTANCE()`。 - -## 可用的文本嵌入模型 - -TiDB Cloud 支持多种嵌入模型。请选择最适合你需求的模型: - -| 嵌入模型 | 文档 | TiDB Cloud 托管 1 | BYOK 2 | -| ------------- | ------------------------------------------------------------------------------------- | ---------------------------- | ----------------- | -| Amazon Titan | [Amazon Titan Embeddings](/tidb-cloud/vector-search-auto-embedding-amazon-titan.md) | ✅ | | -| Cohere | [Cohere Embeddings](/tidb-cloud/vector-search-auto-embedding-cohere.md) | ✅ | ✅ | -| Jina AI | [Jina AI Embeddings](/tidb-cloud/vector-search-auto-embedding-jina-ai.md) | | ✅ | -| OpenAI | [OpenAI Embeddings](/tidb-cloud/vector-search-auto-embedding-openai.md) | | ✅ | -| Gemini | [Gemini Embeddings](/tidb-cloud/vector-search-auto-embedding-gemini.md) | | ✅ | - -你还可以通过 TiDB Cloud 支持的以下推理服务,使用开源嵌入模型: - -| 嵌入模型 | 文档 | TiDB Cloud 托管 1 | BYOK 2 | 示例支持的模型 | -| -------------------- | ------------------------------------------------------------------------------------- | ---------------------------- | ----------------- | ------------------------------- | -| HuggingFace Inference| [HuggingFace Embeddings](/tidb-cloud/vector-search-auto-embedding-huggingface.md) | | ✅ | `bge-m3`, `multilingual-e5-large`| -| NVIDIA NIM | [NVIDIA NIM Embeddings](/tidb-cloud/vector-search-auto-embedding-nvidia-nim.md) | | ✅ | `bge-m3`, `nv-embed-v1` | - -​1 托管模型由 TiDB Cloud 托管,无需任何 API key。目前这些托管模型可免费使用,但可能会施加一定的使用限制,以保证所有用户的可用性。 - -​2 BYOK(Bring Your Own Key)模型需要你从相应的嵌入服务商处提供自己的 API key。TiDB Cloud 不会对 BYOK 模型的使用收费。你需要自行管理和监控使用这些模型所产生的费用。 - -## Auto Embedding 的工作原理 - -Auto Embedding 使用 [`EMBED_TEXT()`](#embed_text) 函数,结合你选择的嵌入模型,将文本转换为向量嵌入。生成的向量存储在 `VECTOR` 列中,并可通过 [`VEC_EMBED_COSINE_DISTANCE()`](#vec_embed_cosine_distance) 或 [`VEC_EMBED_L2_DISTANCE()`](#vec_embed_l2_distance) 使用纯文本进行查询。 - -在内部,[`VEC_EMBED_COSINE_DISTANCE()`](#vec_embed_cosine_distance) 和 [`VEC_EMBED_L2_DISTANCE()`](#vec_embed_l2_distance) 实际执行的是 [`VEC_COSINE_DISTANCE()`](/vector-search/vector-search-functions-and-operators.md#vec_cosine_distance) 和 [`VEC_L2_DISTANCE()`](/vector-search/vector-search-functions-and-operators.md#vec_l2_distance),文本查询会自动转换为向量嵌入。 - -## 关键函数 - -### `EMBED_TEXT()` - -将文本转换为向量嵌入: - -```sql -EMBED_TEXT("model_name", text_content[, additional_json_options]) -``` - -在 `GENERATED ALWAYS AS` 子句中使用该函数,可在插入或更新文本数据时自动生成嵌入。 - -### `VEC_EMBED_COSINE_DISTANCE()` - -计算向量列中已存储向量与文本查询之间的余弦相似度: - -```sql -VEC_EMBED_COSINE_DISTANCE(vector_column, "query_text") -``` - -在 `ORDER BY` 子句中使用该函数,可按余弦距离对结果进行排序。其计算方式与 [`VEC_COSINE_DISTANCE()`](/vector-search/vector-search-functions-and-operators.md#vec_cosine_distance) 相同,但会自动为查询文本生成嵌入。 - -### `VEC_EMBED_L2_DISTANCE()` - -计算已存储向量与文本查询之间的 L2(欧氏)距离: - -```sql -VEC_EMBED_L2_DISTANCE(vector_column, "query_text") -``` - -在 `ORDER BY` 子句中使用该函数,可按 L2 距离对结果进行排序。其计算方式与 [`VEC_L2_DISTANCE()`](/vector-search/vector-search-functions-and-operators.md#vec_l2_distance) 相同,但会自动为查询文本生成嵌入。 - -## 在 Python 中使用 Auto Embedding - -参见 [PyTiDB 文档](https://pingcap.github.io/ai/guides/auto-embedding/)。 - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量函数与操作符](/vector-search/vector-search-functions-and-operators.md) -- [向量搜索索引](/vector-search/vector-search-index.md) diff --git a/tidb-cloud/vector-search-changelogs.md b/tidb-cloud/vector-search-changelogs.md deleted file mode 100644 index 2147283022214..0000000000000 --- a/tidb-cloud/vector-search-changelogs.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Vector Search Changelogs -summary: 了解 TiDB 向量检索功能的新特性、兼容性变更、改进和缺陷修复。 ---- - -# Vector Search Changelogs - -## 2025 年 7 月 15 日 - -- TiDB Vector Search(测试版)现已支持 TiDB Cloud Dedicated(TiDB >= v8.4)集群。 - -## 2024 年 6 月 25 日 - -- TiDB Vector Search(测试版)现已在所有区域的 TiDB Cloud Serverless 集群对所有用户开放。 - -## 2024 年 4 月 1 日 - -- TiDB Vector Search(测试版)现已在欧盟区域的 TiDB Cloud Serverless 集群对受邀用户开放。 \ No newline at end of file diff --git a/tidb-cloud/vector-search-full-text-search-python.md b/tidb-cloud/vector-search-full-text-search-python.md deleted file mode 100644 index 88ffff9999667..0000000000000 --- a/tidb-cloud/vector-search-full-text-search-python.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: 使用 Python 进行全文检索 -summary: 全文检索允许你根据精确的关键词检索文档。在 RAG(检索增强生成)场景中,你可以将全文检索与向量检索结合使用,以提升检索质量。 -aliases: ['/tidb/stable/vector-search-full-text-search-python'] ---- - -# 使用 Python 进行全文检索 - -与关注语义相似度的 [向量检索](/vector-search/vector-search-overview.md) 不同,全文检索允许你根据精确的关键词检索文档。在 RAG(检索增强生成)场景中,你可以将全文检索与向量检索结合使用,以提升检索质量。 - -TiDB 的全文检索功能提供以下能力: - -- **直接查询文本数据**:你可以直接在任意字符串列上进行检索,无需进行嵌入处理。 - -- **多语言支持**:无需指定语言即可获得高质量检索。TiDB 支持在同一张表中存储多种语言的文档,并会为每个文档自动选择最佳的文本分析器。 - -- **按相关性排序**:检索结果可以使用被广泛采用的 [BM25 排序](https://en.wikipedia.org/wiki/Okapi_BM25) 算法按相关性排序。 - -- **完全兼容 SQL**:所有 SQL 功能,如预过滤、后过滤、分组和关联查询,都可以与全文检索结合使用。 - -> **提示:** -> -> 有关 SQL 用法,参见 [使用 SQL 进行全文检索](/tidb-cloud/vector-search-full-text-search-sql.md)。 -> -> 如需在 AI 应用中同时使用全文检索和向量检索,参见 [混合检索](/tidb-cloud/vector-search-hybrid-search.md)。 - -## 前提条件 - -全文检索目前仍处于早期阶段,我们正在持续向更多用户开放。目前,全文检索仅在以下区域的 TiDB Cloud Starter 和 TiDB Cloud Essential 上可用: - -- AWS:`法兰克福 (eu-central-1)` 和 `新加坡 (ap-southeast-1)` - -要完成本教程,请确保你在支持的区域拥有一个 TiDB Cloud Starter 集群。如果还没有,请按照 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建。 - -## 快速开始 - -### 步骤 1. 安装 [pytidb](https://github.com/pingcap/pytidb) Python SDK - -[pytidb](https://github.com/pingcap/pytidb) 是 TiDB 官方的 Python SDK,旨在帮助开发者高效构建 AI 应用。该 SDK 内置了对向量检索和全文检索的支持。 - -安装 SDK,请运行以下命令: - -```shell -pip install pytidb - -# (可选)如需使用内置的 embedding 函数和 reranker: -# pip install "pytidb[models]" - -# (可选)如需将查询结果转换为 pandas DataFrame: -# pip install pandas -``` - -### 步骤 2. 连接 TiDB - -```python -from pytidb import TiDBClient - -db = TiDBClient.connect( - host="HOST_HERE", - port=4000, - username="USERNAME_HERE", - password="PASSWORD_HERE", - database="DATABASE_HERE", -) -``` - -你可以在 [TiDB Cloud 控制台](https://tidbcloud.com) 获取这些连接参数: - -1. 进入 [**Clusters**](https://tidbcloud.com/project/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**。此时会弹出连接对话框,显示连接参数。 - - 例如,连接参数如下所示: - - ```text - HOST: gateway01.us-east-1.prod.shared.aws.tidbcloud.com - PORT: 4000 - USERNAME: 4EfqPF23YKBxaQb.root - PASSWORD: abcd1234 - DATABASE: test - CA: /etc/ssl/cert.pem - ``` - - 对应的 Python 代码如下: - - ```python - db = TiDBClient.connect( - host="gateway01.us-east-1.prod.shared.aws.tidbcloud.com", - port=4000, - username="4EfqPF23YKBxaQb.root", - password="abcd1234", - database="test", - ) - ``` - - 注意,上述示例仅用于演示。你需要使用自己的参数,并妥善保管。 - -### 步骤 3. 创建表和全文索引 - -以创建名为 `chunks` 的表为例,包含以下字段: - -- `id` (int):分块的 ID。 -- `text` (text):分块的文本内容。 -- `user_id` (int):创建该分块的用户 ID。 - -```python -from pytidb.schema import TableModel, Field - -class Chunk(TableModel, table=True): - __tablename__ = "chunks" - - id: int = Field(primary_key=True) - text: str = Field() - user_id: int = Field() - -table = db.create_table(schema=Chunk) - -if not table.has_fts_index("text"): - table.create_fts_index("text") # 👈 在 text 列上创建全文索引。 -``` - -### 步骤 4. 插入数据 - -```python -table.bulk_insert( - [ - Chunk(id=2, text="the quick brown", user_id=2), - Chunk(id=3, text="fox jumps", user_id=3), - Chunk(id=4, text="over the lazy dog", user_id=4), - ] -) -``` - -### 步骤 5. 执行全文检索 - -插入数据后,你可以按如下方式进行全文检索: - -```python -df = ( - table.search("brown fox", search_type="fulltext") - .limit(2) - .to_pandas() # optional -) - -# id text user_id -# 0 3 fox jumps 3 -# 1 2 the quick brown 2 -``` - -完整示例参见 [pytidb full-text search demo](https://github.com/pingcap/pytidb/blob/main/examples/fulltext_search)。 - -## 相关链接 - -- [pytidb Python SDK 文档](https://github.com/pingcap/pytidb) - -- [混合检索](/tidb-cloud/vector-search-hybrid-search.md) - -## 反馈与帮助 - -全文检索目前仍处于早期阶段,开放范围有限。如果你希望在尚未开放的区域体验全文检索,或有任何反馈和帮助需求,欢迎联系我们: - - - -- [加入我们的 Discord](https://discord.gg/zcqexutz2R) - - - - - -- [加入我们的 Discord](https://discord.gg/zcqexutz2R) -- [访问我们的支持门户](https://tidb.support.pingcap.com/) - - diff --git a/tidb-cloud/vector-search-full-text-search-sql.md b/tidb-cloud/vector-search-full-text-search-sql.md deleted file mode 100644 index 5031449c582fb..0000000000000 --- a/tidb-cloud/vector-search-full-text-search-sql.md +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: 使用 SQL 进行全文检索 -summary: 全文检索允许你根据精确关键词检索文档。在 RAG(检索增强生成)场景中,你可以将全文检索与向量检索结合使用,以提升检索质量。 -aliases: ['/tidb/stable/vector-search-full-text-search-sql'] ---- - -# 使用 SQL 进行全文检索 - -与 [向量检索](/vector-search/vector-search-overview.md) 侧重于语义相似性不同,全文检索允许你根据精确关键词检索文档。在 RAG(检索增强生成)场景中,你可以将全文检索与向量检索结合使用,以提升检索质量。 - -TiDB 的全文检索功能提供以下能力: - -- **直接查询文本数据**:你可以直接在任意字符串列上进行检索,无需进行嵌入处理。 - -- **支持多语言**:无需指定语言即可获得高质量检索。TiDB 的文本分析器支持同一张表中多种语言混合的文档,并会自动为每个文档选择最佳分析器。 - -- **按相关性排序**:检索结果可以通过广泛采用的 [BM25 排序](https://en.wikipedia.org/wiki/Okapi_BM25) 算法按相关性排序。 - -- **与 SQL 完全兼容**:所有 SQL 特性,如预过滤、后过滤、分组和关联查询等,都可以与全文检索结合使用。 - -> **提示:** -> -> 关于 Python 的用法,请参见 [使用 Python 进行全文检索](/tidb-cloud/vector-search-full-text-search-python.md)。 -> -> 如需在 AI 应用中同时使用全文检索和向量检索,请参见 [混合检索](/tidb-cloud/vector-search-hybrid-search.md)。 - -## 快速开始 - -全文检索目前仍处于早期阶段,我们正在持续向更多用户开放。目前,全文检索仅在以下区域的 TiDB Cloud Starter 和 TiDB Cloud Essential 上可用: - -- AWS:`法兰克福 (eu-central-1)` 和 `新加坡 (ap-southeast-1)` - -在使用全文检索前,请确保你的 TiDB Cloud Starter 集群已创建在支持的区域。如果还没有,请按照 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 进行创建。 - -要执行全文检索,请按照以下步骤操作: - -1. [**创建全文索引**](#创建全文索引):创建带有全文索引的表,或为已有表添加全文索引。 - -2. [**插入文本数据**](#插入文本数据):向表中插入文本数据。 - -3. [**执行全文检索**](#执行全文检索):使用文本查询和全文检索函数进行全文检索。 - -### 创建全文索引 - -要进行全文检索,需要创建全文索引,它为高效检索和排序提供必要的数据结构。全文索引既可以在新表上创建,也可以添加到已有表中。 - -创建带有全文索引的表: - -```sql -CREATE TABLE stock_items( - id INT, - title TEXT, - FULLTEXT INDEX (title) WITH PARSER MULTILINGUAL -); -``` - -或者为已有表添加全文索引: - -```sql -CREATE TABLE stock_items( - id INT, - title TEXT -); - --- 你可以在这里插入一些数据。 --- 即使表中已有数据,也可以创建全文索引。 - -ALTER TABLE stock_items ADD FULLTEXT INDEX (title) WITH PARSER MULTILINGUAL ADD_COLUMNAR_REPLICA_ON_DEMAND; -``` - -`WITH PARSER ` 子句中支持以下解析器: - -- `STANDARD`:速度快,适用于英文内容,通过空格和标点分词。 - -- `MULTILINGUAL`:支持多种语言,包括英文、中文、日文和韩文。 - -### 插入文本数据 - -向带有全文索引的表插入数据与向其他表插入数据完全相同。 - -例如,你可以执行以下 SQL 语句插入多语言数据。TiDB 的多语言解析器会自动处理这些文本。 - -```sql -INSERT INTO stock_items VALUES (1, "イヤホン bluetooth ワイヤレスイヤホン "); -INSERT INTO stock_items VALUES (2, "完全ワイヤレスイヤホン/ウルトラノイズキャンセリング 2.0 "); -INSERT INTO stock_items VALUES (3, "ワイヤレス ヘッドホン Bluetooth 5.3 65時間再生 ヘッドホン 40mm HD "); -INSERT INTO stock_items VALUES (4, "楽器用 オンイヤーヘッドホン 密閉型【国内正規品】"); -INSERT INTO stock_items VALUES (5, "ワイヤレスイヤホン ハイブリッドANC搭載 40dBまでアクティブノイズキャンセル"); -INSERT INTO stock_items VALUES (6, "Lightweight Bluetooth Earbuds with 48 Hours Playtime"); -INSERT INTO stock_items VALUES (7, "True Wireless Noise Cancelling Earbuds - Compatible with Apple & Android, Built-in Microphone"); -INSERT INTO stock_items VALUES (8, "In-Ear Earbud Headphones with Mic, Black"); -INSERT INTO stock_items VALUES (9, "Wired Headphones, HD Bass Driven Audio, Lightweight Aluminum Wired in Ear Earbud Headphones"); -INSERT INTO stock_items VALUES (10, "LED Light Bar, Music Sync RGB Light Bar, USB Ambient Lamp"); -INSERT INTO stock_items VALUES (11, "无线消噪耳机-黑色 手势触控蓝牙降噪 主动降噪头戴式耳机(智能降噪 长久续航)"); -INSERT INTO stock_items VALUES (12, "专业版USB7.1声道游戏耳机电竞耳麦头戴式电脑网课办公麦克风带线控"); -INSERT INTO stock_items VALUES (13, "投影仪家用智能投影机便携卧室手机投影"); -INSERT INTO stock_items VALUES (14, "无线蓝牙耳机超长续航42小时快速充电 流光金属耳机"); -INSERT INTO stock_items VALUES (15, "皎月银 国家补贴 心率血氧监测 蓝牙通话 智能手表 男女表"); -``` - -### 执行全文检索 - -要执行全文检索,你可以使用 `FTS_MATCH_WORD()` 函数。 - -**示例:检索最相关的 10 个文档** - -```sql -SELECT * FROM stock_items - WHERE fts_match_word("bluetoothイヤホン", title) - ORDER BY fts_match_word("bluetoothイヤホン", title) - DESC LIMIT 10; - --- 结果按相关性排序,最相关的文档排在最前面。 - -+------+-----------------------------------------------------------------------------------------------------------+ -| id | title | -+------+-----------------------------------------------------------------------------------------------------------+ -| 1 | イヤホン bluetooth ワイヤレスイヤホン | -| 6 | Lightweight Bluetooth Earbuds with 48 Hours Playtime | -| 2 | 完全ワイヤレスイヤホン/ウルトラノイズキャンセリング 2.0 | -| 3 | ワイヤレス ヘッドホン Bluetooth 5.3 65時間再生 ヘッドホン 40mm HD | -| 5 | ワイヤレスイヤホン ハイブリッドANC搭载 40dBまでアクティブノイズキャンセル | -+------+-----------------------------------------------------------------------------------------------------------+ - --- 尝试用另一种语言检索: -SELECT * FROM stock_items - WHERE fts_match_word("蓝牙耳机", title) - ORDER BY fts_match_word("蓝牙耳机", title) - DESC LIMIT 10; - --- 结果按相关性排序,最相关的文档排在最前面。 - -+------+---------------------------------------------------------------------------------------------------------------+ -| id | title | -+------+---------------------------------------------------------------------------------------------------------------+ -| 14 | 无线蓝牙耳机超长续航42小时快速充电 流光金属耳机 | -| 11 | 无线消噪耳机-黑色 手势触控蓝牙降噪 主动降噪头戴式耳机(智能降噪 长久续航) | -| 15 | 皎月银 国家补贴 心率血氧监测 蓝牙通话 智能手表 男女表 | -+------+---------------------------------------------------------------------------------------------------------------+ -``` - -**示例:统计与用户查询匹配的文档数量** - -```sql -SELECT COUNT(*) FROM stock_items - WHERE fts_match_word("bluetoothイヤホン", title); - -+----------+ -| COUNT(*) | -+----------+ -| 5 | -+----------+ -``` - -## 进阶示例:与其他表联合检索 - -你可以将全文检索与其他 SQL 特性(如关联查询和子查询)结合使用。 - -假设你有一张 `users` 表和一张 `tickets` 表,并希望根据作者姓名的全文检索结果查找其创建的工单: - -```sql -CREATE TABLE users( - id INT, - name TEXT, - FULLTEXT INDEX (name) WITH PARSER STANDARD -); - -INSERT INTO users VALUES (1, "Alice Smith"); -INSERT INTO users VALUES (2, "Bob Johnson"); - -CREATE TABLE tickets( - id INT, - title TEXT, - author_id INT -); - -INSERT INTO tickets VALUES (1, "Ticket 1", 1); -INSERT INTO tickets VALUES (2, "Ticket 2", 1); -INSERT INTO tickets VALUES (3, "Ticket 3", 2); -``` - -你可以通过子查询根据作者姓名检索匹配的用户 ID,然后在外层查询中使用这些 ID 进行关联,获取相关工单信息: - -```sql -SELECT t.title AS TICKET_TITLE, u.id AS AUTHOR_ID, u.name AS AUTHOR_NAME FROM tickets t -LEFT JOIN users u ON t.author_id = u.id -WHERE t.author_id IN -( - SELECT id FROM users - WHERE fts_match_word("Alice", name) -); - -+--------------+-----------+-------------+ -| TICKET_TITLE | AUTHOR_ID | AUTHOR_NAME | -+--------------+-----------+-------------+ -| Ticket 1 | 1 | Alice Smith | -| Ticket 2 | 1 | Alice Smith | -+--------------+-----------+-------------+ -``` - -## 参见 - -- [混合检索](/tidb-cloud/vector-search-hybrid-search.md) - -## 反馈与帮助 - -全文检索目前仍处于早期阶段,开放范围有限。如果你希望在尚未开放的区域体验全文检索,或有任何反馈与帮助需求,欢迎联系我们: - - - -- [加入我们的 Discord](https://discord.gg/zcqexutz2R) - - - - - -- [加入我们的 Discord](https://discord.gg/zcqexutz2R) -- [访问我们的支持门户](https://tidb.support.pingcap.com/) - - \ No newline at end of file diff --git a/tidb-cloud/vector-search-hybrid-search.md b/tidb-cloud/vector-search-hybrid-search.md deleted file mode 100644 index 5c40806a40b62..0000000000000 --- a/tidb-cloud/vector-search-hybrid-search.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Hybrid Search -summary: 同时使用全文检索和向量检索以提升检索质量。 -aliases: ['/tidb/stable/vector-search-hybrid-search'] ---- - -# Hybrid Search - -通过使用全文检索,你可以基于精确关键词检索文档。通过使用向量检索,你可以基于语义相似度检索文档。那么,我们能否将这两种检索方式结合起来,以提升检索质量并覆盖更多场景?答案是可以,这种方法被称为混合检索(hybrid search),并且在 AI 应用中被广泛使用。 - -在 TiDB 中,混合检索的一般流程如下: - -1. 使用 TiDB 进行 **全文检索** 和 **向量检索**。 -2. 使用 **reranker**(重排序器)对两种检索结果进行融合。 - -![Hybrid Search](/media/vector-search/hybrid-search-overview.svg) - -本教程演示了如何在 TiDB 中使用 [pytidb](https://github.com/pingcap/pytidb) Python SDK 实现混合检索,该 SDK 内置了 embedding 和 reranking 支持。使用 pytidb 并非强制要求 —— 你也可以直接使用 SQL 进行检索,并根据需要使用自定义的 reranking 模型。 - -## 前置条件 - -全文检索目前仍处于早期阶段,我们正在持续向更多用户开放。目前,全文检索仅在以下区域的 TiDB Cloud Starter 和 TiDB Cloud Essential 上可用: - -- AWS: `Frankfurt (eu-central-1)` 和 `Singapore (ap-southeast-1)` - -要完成本教程,请确保你在支持的区域拥有一个 TiDB Cloud Starter 集群。如果还没有,请参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 进行创建。 - -## 快速开始 - -### 步骤 1. 安装 [pytidb](https://github.com/pingcap/pytidb) Python SDK - -```shell -pip install "pytidb[models]" - -# (可选)如果你不想使用内置的 embedding 函数和 reranker: -# pip install pytidb - -# (可选)如需将查询结果转换为 pandas DataFrame: -# pip install pandas -``` - -### 步骤 2. 连接 TiDB - -```python -from pytidb import TiDBClient - -db = TiDBClient.connect( - host="HOST_HERE", - port=4000, - username="USERNAME_HERE", - password="PASSWORD_HERE", - database="DATABASE_HERE", -) -``` - -你可以在 [TiDB Cloud 控制台](https://tidbcloud.com) 获取这些连接参数: - -1. 进入 [**Clusters**](https://tidbcloud.com/project/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框,显示连接参数。 - - 例如,连接参数如下所示: - - ```text - HOST: gateway01.us-east-1.prod.shared.aws.tidbcloud.com - PORT: 4000 - USERNAME: 4EfqPF23YKBxaQb.root - PASSWORD: abcd1234 - DATABASE: test - CA: /etc/ssl/cert.pem - ``` - - 则连接 TiDB Cloud Starter 集群的 Python 代码如下: - - ```python - db = TiDBClient.connect( - host="gateway01.us-east-1.prod.shared.aws.tidbcloud.com", - port=4000, - username="4EfqPF23YKBxaQb.root", - password="abcd1234", - database="test", - ) - ``` - - 注意,上述示例仅用于演示。你需要使用自己的参数,并妥善保管。 - -### 步骤 3. 创建数据表 - -以创建名为 `chunks` 的表为例,包含以下字段: - -- `id` (int):chunk 的 ID。 -- `text` (text):chunk 的文本内容。 -- `text_vec` (vector):文本的向量表示,由 pytidb 中的 embedding 模型自动生成。 -- `user_id` (int):创建该 chunk 的用户 ID。 - -```python -from pytidb.schema import TableModel, Field -from pytidb.embeddings import EmbeddingFunction - -text_embed = EmbeddingFunction("openai/text-embedding-3-small") - -class Chunk(TableModel, table=True): - __tablename__ = "chunks" - - id: int = Field(primary_key=True) - text: str = Field() - text_vec: list[float] = text_embed.VectorField( - source_field="text" - ) # 👈 Define the vector field. - user_id: int = Field() - -table = db.create_table(schema=Chunk) -``` - -### 步骤 4. 插入数据 - -```python -table.bulk_insert( - [ - Chunk(id=2, text="bar", user_id=2), # 👈 The text field will be embedded to a - Chunk(id=3, text="baz", user_id=3), # vector and stored in the "text_vec" field - Chunk(id=4, text="qux", user_id=4), # automatically. - ] -) -``` - -### 步骤 5. 执行混合检索 - -本例中,使用 [jina-reranker](https://huggingface.co/jinaai/jina-reranker-m0) 模型对检索结果进行重排序。 - -```python -from pytidb.rerankers import Reranker - -jinaai = Reranker(model_name="jina_ai/jina-reranker-m0") - -df = ( - table.search("", search_type="hybrid") - .rerank(jinaai, "text") # 👈 Rerank the query result using the jinaai model. - .limit(2) - .to_pandas() -) -``` - -完整示例请参考 [pytidb hybrid search demo](https://github.com/pingcap/pytidb/tree/main/examples/hybrid_search)。 - -## 相关阅读 - -- [pytidb Python SDK 文档](https://github.com/pingcap/pytidb) - -- [使用 Python 进行全文检索](/tidb-cloud/vector-search-full-text-search-python.md) - -## 反馈与帮助 - -全文检索目前仍处于早期阶段,开放范围有限。如果你希望在尚未开放的区域体验全文检索,或有任何反馈与帮助需求,欢迎联系我们: - - - -- [加入我们的 Discord](https://discord.gg/zcqexutz2R) - - - - - -- [加入我们的 Discord](https://discord.gg/zcqexutz2R) -- [访问我们的支持门户](https://tidb.support.pingcap.com/) - - \ No newline at end of file diff --git a/tidb-cloud/vector-search-integrate-with-amazon-bedrock.md b/tidb-cloud/vector-search-integrate-with-amazon-bedrock.md deleted file mode 100644 index 8c9e64eb42d7b..0000000000000 --- a/tidb-cloud/vector-search-integrate-with-amazon-bedrock.md +++ /dev/null @@ -1,321 +0,0 @@ ---- -title: 集成 TiDB 向量检索与 Amazon Bedrock -summary: 学习如何将 TiDB 向量检索与 Amazon Bedrock 集成,构建基于检索增强生成(RAG)的问答机器人。 ---- - -# 集成 TiDB 向量检索与 Amazon Bedrock - -本教程演示如何将 TiDB 的 [向量检索](/vector-search/vector-search-overview.md) 功能与 [Amazon Bedrock](https://aws.amazon.com/bedrock/) 集成,构建基于检索增强生成(RAG)的问答机器人。 - - - -> **Note:** -> -> 向量检索功能目前为 Beta 版本,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -> **Tip** -> -> 你可以在 Notebook 格式下查看完整的 [示例代码](https://github.com/aws-samples/aws-generativeai-partner-samples/blob/main/tidb/samples/tidb-bedrock-boto3-rag.ipynb)。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.11 或更高版本](https://www.python.org/downloads/) -- 已安装 [Pip](https://pypi.org/project/pip/) -- 已安装 [AWS CLI](https://aws.amazon.com/cli/) - - 请确保你的 AWS CLI 配置文件已设置为本教程支持的 [Amazon Bedrock](https://aws.amazon.com/bedrock/) 区域。支持的区域列表可参考 [Amazon Bedrock Regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)。如需切换到支持的区域,可运行以下命令: - - ```shell - aws configure set region - ``` - -- 一个 TiDB Cloud Starter 集群 - - 如果你还没有 TiDB Cloud 集群,请参考[创建 TiDB Cloud Starter 集群](/tidb-cloud/create-tidb-cluster-serverless.md) 创建属于你自己的 TiDB Cloud 集群。 - -- 一个具有 [Amazon Bedrock 所需权限](https://docs.aws.amazon.com/bedrock/latest/userguide/security_iam_id-based-policy-examples.html) 的 AWS 账号,并且能够访问以下模型: - - - **Amazon Titan Embeddings**(`amazon.titan-embed-text-v2:0`),用于生成文本向量 - - **Meta Llama 3**(`us.meta.llama3-2-3b-instruct-v1:0`),用于文本生成 - - 如果你尚未获得访问权限,请按照 [申请访问 Amazon Bedrock 基础模型](https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html#getting-started-model-access) 的说明操作。 - -## 开始使用 - -本节将为你提供将 TiDB 向量检索与 Amazon Bedrock 集成,构建基于 RAG 的问答机器人的分步指南。 - -### 步骤 1. 设置环境变量 - -从 [TiDB Cloud 控制台](https://tidbcloud.com/) 获取 TiDB 连接信息,并在你的开发环境中设置环境变量,操作如下: - -1. 进入 [**Clusters**](https://tidbcloud.com/project/clusters) 页面,点击目标集群名称,进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确保连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public` - - **Branch** 设置为 `main` - - **Connect With** 设置为 `General` - - **Operating System** 与你的环境一致 - - > **Tip:** - > - > 如果你的程序运行在 Windows Subsystem for Linux (WSL) 中,请切换到对应的 Linux 发行版。 - -4. 点击 **Generate Password** 生成随机密码。 - - > **Tip:** - > - > 如果你之前已创建过密码,可以继续使用原密码,或点击 **Reset Password** 生成新密码。 - -5. 在终端中运行以下命令设置环境变量。你需要将命令中的占位符替换为连接对话框中获取的对应参数。 - - ```shell - export TIDB_HOST= - export TIDB_PORT=4000 - export TIDB_USER= - export TIDB_PASSWORD= - export TIDB_DB_NAME=test - ``` - -### 步骤 2. 配置 Python 虚拟环境 - -1. 创建一个名为 `demo.py` 的 Python 文件: - - ```shell - touch demo.py - ``` - -2. 创建并激活虚拟环境以管理依赖: - - ```shell - python3 -m venv env - source env/bin/activate # 在 Windows 上使用 env\Scripts\activate - ``` - -3. 安装所需依赖: - - ```shell - pip install SQLAlchemy==2.0.30 PyMySQL==1.1.0 tidb-vector==0.0.9 pydantic==2.7.1 boto3 - ``` - -### 步骤 3. 导入所需库 - -在 `demo.py` 文件开头添加以下代码以导入所需库: - -```python -import os -import json -import boto3 -from sqlalchemy import Column, Integer, Text, create_engine -from sqlalchemy.orm import declarative_base, Session -from tidb_vector.sqlalchemy import VectorType -``` - -### 步骤 4. 配置数据库连接 - -在 `demo.py` 中添加以下代码以配置数据库连接: - -```python -# ---- Configuration Setup ---- -# Set environment variables: TIDB_HOST, TIDB_PORT, TIDB_USER, TIDB_PASSWORD, TIDB_DB_NAME -TIDB_HOST = os.environ.get("TIDB_HOST") -TIDB_PORT = os.environ.get("TIDB_PORT") -TIDB_USER = os.environ.get("TIDB_USER") -TIDB_PASSWORD = os.environ.get("TIDB_PASSWORD") -TIDB_DB_NAME = os.environ.get("TIDB_DB_NAME") - -# ---- Database Setup ---- -def get_db_url(): - """Build the database connection URL.""" - return f"mysql+pymysql://{TIDB_USER}:{TIDB_PASSWORD}@{TIDB_HOST}:{TIDB_PORT}/{TIDB_DB_NAME}?ssl_verify_cert=True&ssl_verify_identity=True" - -# Create engine -engine = create_engine(get_db_url(), pool_recycle=300) -Base = declarative_base() -``` - -### 步骤 5. 通过 Bedrock runtime client 调用 Amazon Titan Text Embeddings V2 模型 - -Amazon Bedrock runtime client 提供了 `invoke_model` API,接受以下参数: - -- `modelId`:Amazon Bedrock 可用基础模型的模型 ID -- `accept`:输入请求的类型 -- `contentType`:输入内容的类型 -- `body`:包含 prompt 和配置的 JSON 字符串负载 - -在 `demo.py` 中添加以下代码,通过 `invoke_model` API 使用 Amazon Titan Text Embeddings 生成文本向量,并通过 Meta Llama 3 获取响应: - -```python -# Bedrock Runtime Client Setup -bedrock_runtime = boto3.client('bedrock-runtime') - -# ---- Model Invocation ---- -embedding_model_name = "amazon.titan-embed-text-v2:0" -dim_of_embedding_model = 512 -llm_name = "us.meta.llama3-2-3b-instruct-v1:0" - - -def embedding(content): - """Invoke Amazon Bedrock to get text embeddings.""" - payload = { - "modelId": embedding_model_name, - "contentType": "application/json", - "accept": "*/*", - "body": { - "inputText": content, - "dimensions": dim_of_embedding_model, - "normalize": True, - } - } - - body_bytes = json.dumps(payload['body']).encode('utf-8') - - response = bedrock_runtime.invoke_model( - body=body_bytes, - contentType=payload['contentType'], - accept=payload['accept'], - modelId=payload['modelId'] - ) - - result_body = json.loads(response.get("body").read()) - return result_body.get("embedding") - - -def generate_result(query: str, info_str: str): - """Generate answer using Meta Llama 3 model.""" - prompt = f""" - ONLY use the content below to generate an answer: - {info_str} - - ---- - Please carefully think about the question: {query} - """ - - payload = { - "modelId": llm_name, - "contentType": "application/json", - "accept": "application/json", - "body": { - "prompt": prompt, - "temperature": 0 - } - } - - body_bytes = json.dumps(payload['body']).encode('utf-8') - - response = bedrock_runtime.invoke_model( - body=body_bytes, - contentType=payload['contentType'], - accept=payload['accept'], - modelId=payload['modelId'] - ) - - result_body = json.loads(response.get("body").read()) - completion = result_body["generation"] - return completion -``` - -### 步骤 6. 创建向量表 - -在 `demo.py` 中添加以下代码,创建用于存储文本及其向量的向量表: - -```python -# ---- TiDB Setup and Vector Index Creation ---- -class Entity(Base): - """Define the Entity table with a vector index.""" - __tablename__ = "entity" - id = Column(Integer, primary_key=True) - content = Column(Text) - content_vec = Column(VectorType(dim=dim_of_embedding_model), comment="hnsw(distance=l2)") - -# Create the table in TiDB -Base.metadata.create_all(engine) -``` - -### 步骤 7. 将向量数据保存到 TiDB Cloud Starter - -在 `demo.py` 中添加以下代码,将向量数据保存到你的 TiDB Cloud Starter 集群: - -```python -# ---- Saving Vectors to TiDB ---- -def save_entities_with_embedding(session, contents): - """Save multiple entities with their embeddings to the TiDB database.""" - for content in contents: - entity = Entity(content=content, content_vec=embedding(content)) - session.add(entity) - session.commit() -``` - -### 步骤 8. 运行应用 - -1. 在 `demo.py` 中添加以下代码,建立数据库会话,将向量保存到 TiDB,提出示例问题(如 "What is TiDB?"),并从模型生成结果: - - ```python - if __name__ == "__main__": - # Establish a database session - with Session(engine) as session: - # Example data - contents = [ - "TiDB is a distributed SQL database compatible with MySQL.", - "TiDB supports Hybrid Transactional and Analytical Processing (HTAP).", - "TiDB can scale horizontally and provides high availability.", - "Amazon Bedrock allows seamless integration with foundation models.", - "Meta Llama 3 is a powerful model for text generation." - ] - - # Save embeddings to TiDB - save_entities_with_embedding(session, contents) - - # Example query - query = "What is TiDB?" - info_str = " ".join(contents) - - # Generate result from Meta Llama 3 - result = generate_result(query, info_str) - print(f"Generated answer: {result}") - ``` - -2. 保存所有对 `demo.py` 的更改并运行脚本: - - ```shell - python3 demo.py - ``` - - 预期输出类似如下: - - ``` - Generated answer: What is the main purpose of TiDB? - What are the key features of TiDB? - What are the key benefits of TiDB? - - ---- - Based on the provided text, here is the answer to the question: - What is TiDB? - TiDB is a distributed SQL database compatible with MySQL. - - ## Step 1: Understand the question - The question asks for the definition of TiDB. - - ## Step 2: Identify the key information - The key information provided in the text is that TiDB is a distributed SQL database compatible with MySQL. - - ## Step 3: Provide the answer - Based on the provided text, TiDB is a distributed SQL database compatible with MySQL. - - The final answer is: TiDB is a distributed SQL database compatible with MySQL. - ``` - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-data-types.md b/vector-search/vector-search-data-types.md deleted file mode 100644 index 94846658dc31f..0000000000000 --- a/vector-search/vector-search-data-types.md +++ /dev/null @@ -1,262 +0,0 @@ ---- -title: Vector Data Types -summary: 了解 TiDB 中的 Vector 数据类型。 ---- - -# Vector 数据类型 - -向量(Vector)是一组浮点数的序列,例如 `[0.3, 0.5, -0.1, ...]`。TiDB 提供了 Vector 数据类型,专门针对高效存储和查询在 AI 应用中广泛使用的向量嵌入进行了优化。 - - - -> **Warning:** -> -> 该功能为实验性特性。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 该功能为 Beta 版本,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> Vector 数据类型可用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -目前支持以下 Vector 数据类型: - -- `VECTOR`:任意维度的单精度浮点数序列。 -- `VECTOR(D)`:固定维度 `D` 的单精度浮点数序列。 - -与使用 [`JSON`](/data-type-json.md) 类型相比,使用 Vector 数据类型具有以下优势: - -- 支持向量索引:你可以构建 [向量检索索引](/vector-search/vector-search-index.md) 以加速向量检索。 -- 维度约束:你可以指定维度,禁止插入不同维度的向量。 -- 优化的存储格式:Vector 数据类型针对向量数据进行了优化,空间效率和性能优于 `JSON` 类型。 - -## 语法 - -你可以使用如下语法的字符串来表示一个 Vector 值: - -```sql -'[, , ...]' -``` - -示例: - -```sql -CREATE TABLE vector_table ( - id INT PRIMARY KEY, - embedding VECTOR(3) -); - -INSERT INTO vector_table VALUES (1, '[0.3, 0.5, -0.1]'); - -INSERT INTO vector_table VALUES (2, NULL); -``` - -插入语法不合法的向量值会报错: - -```sql -[tidb]> INSERT INTO vector_table VALUES (3, '[5, ]'); -ERROR 1105 (HY000): Invalid vector text: [5, ] -``` - -在以下示例中,由于在建表时为 `embedding` 列指定了维度 `3`,插入不同维度的向量会报错: - -```sql -[tidb]> INSERT INTO vector_table VALUES (4, '[0.3, 0.5]'); -ERROR 1105 (HY000): vector has 2 dimensions, does not fit VECTOR(3) -``` - -关于 Vector 数据类型可用的函数和操作符,参见 [Vector Functions and Operators](/vector-search/vector-search-functions-and-operators.md)。 - -关于如何构建和使用向量检索索引,参见 [Vector Search Index](/vector-search/vector-search-index.md)。 - -## 存储不同维度的向量 - -你可以通过在 `VECTOR` 类型中省略维度参数,在同一列中存储不同维度的向量: - -```sql -CREATE TABLE vector_table ( - id INT PRIMARY KEY, - embedding VECTOR -); - -INSERT INTO vector_table VALUES (1, '[0.3, 0.5, -0.1]'); -- 3 维向量,OK -INSERT INTO vector_table VALUES (2, '[0.3, 0.5]'); -- 2 维向量,OK -``` - -但需要注意的是,你无法为该列构建 [向量检索索引](/vector-search/vector-search-index.md),因为只有相同维度的向量之间才能计算向量距离。 - -## 比较 - -你可以使用 [比较操作符](/functions-and-operators/operators.md)(如 `=`, `!=`, `<`, `>`, `<=`, `>=`)对 Vector 数据类型进行比较。关于 Vector 数据类型的完整比较操作符和函数列表,参见 [Vector Functions and Operators](/vector-search/vector-search-functions-and-operators.md)。 - -Vector 数据类型按元素逐个进行数值比较。例如: - -- `[1] < [12]` -- `[1,2,3] < [1,2,5]` -- `[1,2,3] = [1,2,3]` -- `[2,2,3] > [1,2,3]` - -对于不同维度的两个向量,采用字典序比较,规则如下: - -- 两个向量从头开始逐元素进行数值比较。 -- 第一个不相等的元素决定哪个向量在字典序上 _更小_ 或 _更大_。 -- 如果一个向量是另一个向量的前缀,则较短的向量在字典序上 _更小_。例如,`[1,2,3] < [1,2,3,0]`。 -- 长度相同且元素完全相同的两个向量在字典序上 _相等_。 -- 空向量在字典序上 _小于_ 任何非空向量。例如,`[] < [1]`。 -- 两个空向量在字典序上 _相等_。 - -在比较向量常量时,建议进行 [显式类型转换](#cast),将字符串转换为向量,以避免基于字符串值的比较: - -```sql --- 由于传入的是字符串,TiDB 按字符串进行比较: -[tidb]> SELECT '[12.0]' < '[4.0]'; -+--------------------+ -| '[12.0]' < '[4.0]' | -+--------------------+ -| 1 | -+--------------------+ -1 row in set (0.01 sec) - --- 显式转换为向量后按向量数值比较: -[tidb]> SELECT VEC_FROM_TEXT('[12.0]') < VEC_FROM_TEXT('[4.0]'); -+--------------------------------------------------+ -| VEC_FROM_TEXT('[12.0]') < VEC_FROM_TEXT('[4.0]') | -+--------------------------------------------------+ -| 0 | -+--------------------------------------------------+ -1 row in set (0.01 sec) -``` - -## 算术运算 - -Vector 数据类型支持 `+`(加法)和 `-`(减法)算术运算。但不支持不同维度的向量之间进行算术运算,否则会报错。 - -示例: - -```sql -[tidb]> SELECT VEC_FROM_TEXT('[4]') + VEC_FROM_TEXT('[5]'); -+---------------------------------------------+ -| VEC_FROM_TEXT('[4]') + VEC_FROM_TEXT('[5]') | -+---------------------------------------------+ -| [9] | -+---------------------------------------------+ -1 row in set (0.01 sec) - -[tidb]> SELECT VEC_FROM_TEXT('[2,3,4]') - VEC_FROM_TEXT('[1,2,3]'); -+-----------------------------------------------------+ -| VEC_FROM_TEXT('[2,3,4]') - VEC_FROM_TEXT('[1,2,3]') | -+-----------------------------------------------------+ -| [1,1,1] | -+-----------------------------------------------------+ -1 row in set (0.01 sec) - -[tidb]> SELECT VEC_FROM_TEXT('[4]') + VEC_FROM_TEXT('[1,2,3]'); -ERROR 1105 (HY000): vectors have different dimensions: 1 and 3 -``` - -## 类型转换 - -### Vector ⇔ String 之间的类型转换 - -要在 Vector 和 String 之间进行类型转换,可以使用以下函数: - -- `CAST(... AS VECTOR)`:String ⇒ Vector -- `CAST(... AS CHAR)`:Vector ⇒ String -- `VEC_FROM_TEXT`:String ⇒ Vector -- `VEC_AS_TEXT`:Vector ⇒ String - -为提升易用性,如果你调用的函数只支持 Vector 数据类型(如向量相关距离函数),也可以直接传入符合格式的字符串,TiDB 会自动进行隐式类型转换。 - -```sql --- VEC_DIMS 函数只接受 VECTOR 参数,因此可以直接传入字符串进行隐式转换。 -[tidb]> SELECT VEC_DIMS('[0.3, 0.5, -0.1]'); -+------------------------------+ -| VEC_DIMS('[0.3, 0.5, -0.1]') | -+------------------------------+ -| 3 | -+------------------------------+ -1 row in set (0.01 sec) - --- 你也可以显式使用 VEC_FROM_TEXT 将字符串转换为向量,再传递给 VEC_DIMS 函数。 -[tidb]> SELECT VEC_DIMS(VEC_FROM_TEXT('[0.3, 0.5, -0.1]')); -+---------------------------------------------+ -| VEC_DIMS(VEC_FROM_TEXT('[0.3, 0.5, -0.1]')) | -+---------------------------------------------+ -| 3 | -+---------------------------------------------+ -1 row in set (0.01 sec) - --- 也可以使用 CAST(... AS VECTOR) 进行显式转换: -[tidb]> SELECT VEC_DIMS(CAST('[0.3, 0.5, -0.1]' AS VECTOR)); -+----------------------------------------------+ -| VEC_DIMS(CAST('[0.3, 0.5, -0.1]' AS VECTOR)) | -+----------------------------------------------+ -| 3 | -+----------------------------------------------+ -1 row in set (0.01 sec) -``` - -当你使用支持多种数据类型的操作符或函数时,需要在将字符串传递给该操作符或函数前,显式将字符串类型转换为向量类型,因为此时 TiDB 不会进行隐式类型转换。例如,在进行比较操作前,需要显式将字符串转换为向量,否则 TiDB 会按字符串值进行比较,而不是按向量数值进行比较: - -```sql --- 由于传入的是字符串,TiDB 按字符串进行比较: -[tidb]> SELECT '[12.0]' < '[4.0]'; -+--------------------+ -| '[12.0]' < '[4.0]' | -+--------------------+ -| 1 | -+--------------------+ -1 row in set (0.01 sec) - --- 显式转换为向量后按向量数值比较: -[tidb]> SELECT VEC_FROM_TEXT('[12.0]') < VEC_FROM_TEXT('[4.0]'); -+--------------------------------------------------+ -| VEC_FROM_TEXT('[12.0]') < VEC_FROM_TEXT('[4.0]') | -+--------------------------------------------------+ -| 0 | -+--------------------------------------------------+ -1 row in set (0.01 sec) -``` - -你也可以将向量显式转换为其字符串表示。例如,使用 `VEC_AS_TEXT()` 函数: - -```sql --- 字符串首先被隐式转换为向量,然后向量被显式转换为字符串,返回规范化格式的字符串: -[tidb]> SELECT VEC_AS_TEXT('[0.3, 0.5, -0.1]'); -+--------------------------------------+ -| VEC_AS_TEXT('[0.3, 0.5, -0.1]') | -+--------------------------------------+ -| [0.3,0.5,-0.1] | -+--------------------------------------+ -1 row in set (0.01 sec) -``` - -更多类型转换函数,参见 [Vector Functions and Operators](/vector-search/vector-search-functions-and-operators.md)。 - -### Vector ⇔ 其他数据类型之间的类型转换 - -目前不支持 Vector 与其他数据类型(如 `JSON`)之间的直接类型转换。你可以在 SQL 语句中通过 String 作为中间类型进行转换来实现类似需求。 - -需要注意的是,表中存储的 Vector 类型列无法通过 `ALTER TABLE ... MODIFY COLUMN ...` 转换为其他数据类型。 - -## 限制 - -关于 Vector 数据类型的限制,参见 [向量检索限制](/vector-search/vector-search-limitations.md) 和 [向量索引限制](/vector-search/vector-search-index.md#restrictions)。 - -## MySQL 兼容性 - -Vector 数据类型为 TiDB 特有,MySQL 不支持该类型。 - -## 参见 - -- [Vector Functions and Operators](/vector-search/vector-search-functions-and-operators.md) -- [Vector Search Index](/vector-search/vector-search-index.md) -- [提升向量检索性能](/vector-search/vector-search-improve-performance.md) diff --git a/vector-search/vector-search-functions-and-operators.md b/vector-search/vector-search-functions-and-operators.md deleted file mode 100644 index afe6cdd26af2c..0000000000000 --- a/vector-search/vector-search-functions-and-operators.md +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: 向量函数与运算符 -summary: 了解可用于向量数据类型的函数与运算符。 ---- - -# 向量函数与运算符 - -本文档列出了可用于向量数据类型的函数与运算符。 - - - -> **Warning:** -> -> 此功能为实验性功能。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交一个 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 此功能处于 beta 阶段,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交一个 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量数据类型及这些向量函数可用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 向量函数 - -以下函数专为 [向量数据类型](/vector-search/vector-search-data-types.md) 设计。 - -**向量距离函数:** - -| 函数名 | 描述 | [向量索引](/vector-search/vector-search-index.md#vector-search-index) 支持 | -| ---------------------------------------------------- | --------------------------------------------------------- |---------------------------| -| [`VEC_L2_DISTANCE`](#vec_l2_distance) | 计算两个向量之间的 L2 距离(欧氏距离) | 是 | -| [`VEC_COSINE_DISTANCE`](#vec_cosine_distance) | 计算两个向量之间的余弦距离 | 是 | -| [`VEC_NEGATIVE_INNER_PRODUCT`](#vec_negative_inner_product) | 计算两个向量内积的相反数 | 否 | -| [`VEC_L1_DISTANCE`](#vec_l1_distance) | 计算两个向量之间的 L1 距离(曼哈顿距离) | 否 | - -**其他向量函数:** - -| 函数名 | 描述 | -| ----------------------------- | -------------------------------------------- | -| [`VEC_DIMS`](#vec_dims) | 返回向量的维度 | -| [`VEC_L2_NORM`](#vec_l2_norm) | 计算向量的 L2 范数(欧氏范数) | -| [`VEC_FROM_TEXT`](#vec_from_text) | 将字符串转换为向量 | -| [`VEC_AS_TEXT`](#vec_as_text) | 将向量转换为字符串 | - -## 扩展的内置函数与运算符 - -以下内置函数与运算符已扩展以支持对 [向量数据类型](/vector-search/vector-search-data-types.md) 的操作。 - -**算术运算符:** - -| 名称 | 描述 | -| :------------------------------------------------------------------------------------- | :------------------------------- | -| [`+`](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_plus) | 向量按元素加法运算符 | -| [`-`](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_minus) | 向量按元素减法运算符 | - -关于向量算术的更多信息,参见 [向量数据类型 | 算术运算](/vector-search/vector-search-data-types.md#arithmetic)。 - -**聚合(GROUP BY)函数:** - -| 名称 | 描述 | -| :----------------------- | :---------------------------------------- | -| [`COUNT()`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_count) | 返回结果行数 | -| [`COUNT(DISTINCT)`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_count-distinct) | 返回不同值的数量 | -| [`MAX()`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_max) | 返回最大值 | -| [`MIN()`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_min) | 返回最小值 | - -**比较函数与运算符:** - -| 名称 | 描述 | -| ---------------------------------------- | ---------------------------------------------- | -| [`BETWEEN ... AND ...`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_between) | 检查值是否在某个范围内 | -| [`COALESCE()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce) | 返回第一个非 NULL 的参数 | -| [`=`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_equal) | 等于运算符 | -| [`<=>`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_equal-to) | NULL 安全等于运算符 | -| [`>`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_greater-than) | 大于运算符 | -| [`>=`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_greater-than-or-equal) | 大于等于运算符 | -| [`GREATEST()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_greatest) | 返回最大参数 | -| [`IN()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_in) | 检查值是否在某个集合中 | -| [`IS NULL`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_is-null) | 判断值是否为 `NULL` | -| [`ISNULL()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_isnull) | 判断参数是否为 `NULL` | -| [`LEAST()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_least) | 返回最小参数 | -| [`<`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_less-than) | 小于运算符 | -| [`<=`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_less-than-or-equal) | 小于等于运算符 | -| [`NOT BETWEEN ... AND ...`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_not-between) | 检查值是否不在某个范围内 | -| [`!=`, `<>`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_not-equal) | 不等于运算符 | -| [`NOT IN()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_not-in) | 检查值是否不在某个集合中 | - -关于向量比较的更多信息,参见 [向量数据类型 | 比较](/vector-search/vector-search-data-types.md#comparison)。 - -**流程控制函数:** - -| 名称 | 描述 | -| :------------------------------------------------------------------------------------------------ | :-------------------- | -| [`CASE`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#operator_case) | CASE 运算符 | -| [`IF()`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_if) | IF/ELSE 结构 | -| [`IFNULL()`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull) | NULL IF/ELSE 结构 | -| [`NULLIF()`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_nullif) | 如果 expr1 = expr2 则返回 `NULL` | - -**类型转换函数:** - -| 名称 | 描述 | -| :------------------------------------------------------------------------------------------ | :-------------------------- | -| [`CAST()`](https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast) | 将值转换为字符串或向量 | -| [`CONVERT()`](https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_convert) | 将值转换为字符串 | - -关于如何使用 `CAST()` 的更多信息,参见 [向量数据类型 | 类型转换](/vector-search/vector-search-data-types.md#cast)。 - -## 完整参考 - -### VEC_L2_DISTANCE - -```sql -VEC_L2_DISTANCE(vector1, vector2) -``` - -使用以下公式计算两个向量之间的 [L2 距离](https://en.wikipedia.org/wiki/Euclidean_distance)(欧氏距离): - -$DISTANCE(p,q)=\sqrt {\sum \limits _{i=1}^{n}{(p_{i}-q_{i})^{2}}}$ - -两个向量必须具有相同的维度,否则会返回错误。 - -示例: - -```sql -SELECT VEC_L2_DISTANCE('[0, 3]', '[4, 0]'); -``` - -``` -+-------------------------------------+ -| VEC_L2_DISTANCE('[0, 3]', '[4, 0]') | -+-------------------------------------+ -| 5 | -+-------------------------------------+ -``` - -### VEC_COSINE_DISTANCE - -```sql -VEC_COSINE_DISTANCE(vector1, vector2) -``` - -使用以下公式计算两个向量之间的 [余弦距离](https://en.wikipedia.org/wiki/Cosine_similarity): - -$DISTANCE(p,q)=1.0 - {\frac {\sum \limits _{i=1}^{n}{p_{i}q_{i}}}{{\sqrt {\sum \limits _{i=1}^{n}{p_{i}^{2}}}}\cdot {\sqrt {\sum \limits _{i=1}^{n}{q_{i}^{2}}}}}}$ - -两个向量必须具有相同的维度,否则会返回错误。 - -对于来自 OpenAI 的嵌入向量,[推荐](https://help.openai.com/en/articles/6824809-embeddings-faq)使用此函数。 - -示例: - -```sql -SELECT VEC_COSINE_DISTANCE('[1, 1]', '[-1, -1]'); -``` - -``` -+-------------------------------------------+ -| VEC_COSINE_DISTANCE('[1, 1]', '[-1, -1]') | -+-------------------------------------------+ -| 2 | -+-------------------------------------------+ -``` - -### VEC_NEGATIVE_INNER_PRODUCT - -```sql -VEC_NEGATIVE_INNER_PRODUCT(vector1, vector2) -``` - -使用以下公式,通过计算两个向量 [内积](https://en.wikipedia.org/wiki/Dot_product) 的相反数来计算距离: - -$DISTANCE(p,q)=- INNER\_PROD(p,q)=-\sum \limits _{i=1}^{n}{p_{i}q_{i}}$ - -两个向量必须具有相同的维度,否则会返回错误。 - -示例: - -```sql -SELECT VEC_NEGATIVE_INNER_PRODUCT('[1, 2]', '[3, 4]'); -``` - -``` -+------------------------------------------------+ -| VEC_NEGATIVE_INNER_PRODUCT('[1, 2]', '[3, 4]') | -+------------------------------------------------+ -| -11 | -+------------------------------------------------+ -``` - -### VEC_L1_DISTANCE - -```sql -VEC_L1_DISTANCE(vector1, vector2) -``` - -使用以下公式计算两个向量之间的 [L1 距离](https://en.wikipedia.org/wiki/Taxicab_geometry)(曼哈顿距离): - -$DISTANCE(p,q)=\sum \limits _{i=1}^{n}{|p_{i}-q_{i}|}$ - -两个向量必须具有相同的维度,否则会返回错误。 - -示例: - -```sql -SELECT VEC_L1_DISTANCE('[0, 0]', '[3, 4]'); -``` - -``` -+-------------------------------------+ -| VEC_L1_DISTANCE('[0, 0]', '[3, 4]') | -+-------------------------------------+ -| 7 | -+-------------------------------------+ -``` - -### VEC_DIMS - -```sql -VEC_DIMS(vector) -``` - -返回向量的维度。 - -示例: - -```sql -SELECT VEC_DIMS('[1, 2, 3]'); -``` - -``` -+-----------------------+ -| VEC_DIMS('[1, 2, 3]') | -+-----------------------+ -| 3 | -+-----------------------+ -``` - -```sql -SELECT VEC_DIMS('[]'); -``` - -``` -+----------------+ -| VEC_DIMS('[]') | -+----------------+ -| 0 | -+----------------+ -``` - -### VEC_L2_NORM - -```sql -VEC_L2_NORM(vector) -``` - -使用以下公式计算向量的 [L2 范数](https://en.wikipedia.org/wiki/Norm_(mathematics))(欧氏范数): - -$NORM(p)=\sqrt {\sum \limits _{i=1}^{n}{p_{i}^{2}}}$ - -示例: - -```sql -SELECT VEC_L2_NORM('[3, 4]'); -``` - -``` -+-----------------------+ -| VEC_L2_NORM('[3, 4]') | -+-----------------------+ -| 5 | -+-----------------------+ -``` - -### VEC_FROM_TEXT - -```sql -VEC_FROM_TEXT(string) -``` - -将字符串转换为向量。在许多情况下,此转换是隐式完成的,例如在向 `VECTOR` 数据类型的列中插入数据时。然而,在某些表达式中(如向量的算术运算),如果不支持隐式转换,则需要显式调用此函数。 - -示例: - -```sql -SELECT VEC_FROM_TEXT('[1, 2]') + VEC_FROM_TEXT('[3, 4]'); -``` - -``` -+-------------------------------------------------+ -| VEC_FROM_TEXT('[1,2]') + VEC_FROM_TEXT('[3,4]') | -+-------------------------------------------------+ -| [4,6] | -+-------------------------------------------------+ -``` - -### VEC_AS_TEXT - -```sql -VEC_AS_TEXT(vector) -``` - -将向量转换为字符串。 - -示例: - -```sql -SELECT VEC_AS_TEXT('[1.000, 2.5]'); -``` - -``` -+-----------------------------+ -| VEC_AS_TEXT('[1.000, 2.5]') | -+-----------------------------+ -| [1,2.5] | -+-----------------------------+ -``` - -## MySQL 兼容性 - -向量函数以及内置函数和运算符在向量数据类型上的扩展用法为 TiDB 特有,MySQL 不支持。 - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) diff --git a/vector-search/vector-search-get-started-using-python.md b/vector-search/vector-search-get-started-using-python.md deleted file mode 100644 index eb55d869c7439..0000000000000 --- a/vector-search/vector-search-get-started-using-python.md +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: 使用 Python 快速上手 TiDB + AI -summary: 学习如何使用 Python 和 TiDB 向量检索快速开发一个实现语义搜索的 AI 应用。 ---- - -# 使用 Python 快速上手 TiDB + AI - -本教程演示如何开发一个简单的 AI 应用,实现**语义搜索**功能。与传统的关键词搜索不同,语义搜索能够智能理解你的查询意图,并返回最相关的结果。例如,如果你有标题为 "dog"、"fish" 和 "tree" 的文档,当你搜索 "a swimming animal" 时,应用会识别出 "fish" 是最相关的结果。 - -在本教程中,你将使用 [TiDB Vector Search](/vector-search/vector-search-overview.md)、Python、[TiDB Vector SDK for Python](https://github.com/pingcap/tidb-vector-python) 以及 AI 模型来开发该 AI 应用。 - - - -> **Warning:** -> -> 向量检索功能目前为实验性特性。不建议在生产环境中使用。该功能可能会在未提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能目前为 Beta 版本,可能会在未提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能支持 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 快速上手 - -以下步骤展示了如何从零开发该应用。如果你想直接运行示例代码,可以参考 [pingcap/tidb-vector-python](https://github.com/pingcap/tidb-vector-python/blob/main/examples/python-client-quickstart) 仓库中的示例代码。 - -### 步骤 1. 创建新的 Python 项目 - -在你喜欢的目录下,创建一个新的 Python 项目,并新建一个名为 `example.py` 的文件: - -```shell -mkdir python-client-quickstart -cd python-client-quickstart -touch example.py -``` - -### 步骤 2. 安装所需依赖 - -在你的项目目录下,运行以下命令安装所需的依赖包: - -```shell -pip install sqlalchemy pymysql sentence-transformers tidb-vector python-dotenv -``` - -- `tidb-vector`:用于与 TiDB 向量检索交互的 Python 客户端。 -- [`sentence-transformers`](https://sbert.net):一个 Python 库,提供用于从文本生成[向量嵌入](/vector-search/vector-search-overview.md#vector-embedding)的预训练模型。 - -### 步骤 3. 配置 TiDB 集群连接字符串 - -根据你选择的 TiDB 部署方式,配置集群连接字符串。 - - -
- -对于 TiDB Cloud Starter 集群,按以下步骤获取集群连接字符串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确保连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public`。 - - **Branch** 设置为 `main`。 - - **Connect With** 设置为 `SQLAlchemy`。 - - **Operating System** 与你的环境一致。 - - > **Tip:** - > - > 如果你的程序运行在 Windows Subsystem for Linux (WSL) 中,请切换到对应的 Linux 发行版。 - -4. 点击 **PyMySQL** 标签页并复制连接字符串。 - - > **Tip:** - > - > 如果你还未设置密码,可以点击 **Generate Password** 生成随机密码。 - -5. 在你的 Python 项目根目录下创建 `.env` 文件,并将连接字符串粘贴进去。 - - 以下是 macOS 的示例: - - ```dotenv - TIDB_DATABASE_URL="mysql+pymysql://.root:@gateway01..prod.aws.tidbcloud.com:4000/test?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" - ``` - -
-
- -对于 TiDB 自建集群,在你的 Python 项目根目录下创建 `.env` 文件。将以下内容复制到 `.env` 文件中,并根据你的 TiDB 集群连接参数修改环境变量的值: - -```dotenv -TIDB_DATABASE_URL="mysql+pymysql://:@:/" -# 例如:TIDB_DATABASE_URL="mysql+pymysql://root@127.0.0.1:4000/test" -``` - -如果你在本地运行 TiDB,`` 默认为 `127.0.0.1`。初始 `` 为空,因此如果你是首次启动集群,可以省略该字段。 - -各参数说明如下: - -- ``:连接 TiDB 集群的用户名。 -- ``:连接 TiDB 集群的密码。 -- ``:TiDB 集群的主机地址。 -- ``:TiDB 集群的端口号。 -- ``:你要连接的数据库名称。 - -
- -
- -### 步骤 4. 初始化嵌入模型 - -[嵌入模型](/vector-search/vector-search-overview.md#embedding-model)用于将数据转换为[向量嵌入](/vector-search/vector-search-overview.md#vector-embedding)。本示例使用预训练模型 [**msmarco-MiniLM-L12-cos-v5**](https://huggingface.co/sentence-transformers/msmarco-MiniLM-L12-cos-v5) 进行文本嵌入。该轻量级模型由 `sentence-transformers` 库提供,可将文本数据转换为 384 维的向量嵌入。 - -要设置模型,将以下代码复制到 `example.py` 文件中。该代码初始化了一个 `SentenceTransformer` 实例,并定义了后续使用的 `text_to_embedding()` 函数。 - -```python -from sentence_transformers import SentenceTransformer - -print("Downloading and loading the embedding model...") -embed_model = SentenceTransformer("sentence-transformers/msmarco-MiniLM-L12-cos-v5", trust_remote_code=True) -embed_model_dims = embed_model.get_sentence_embedding_dimension() - -def text_to_embedding(text): - """Generates vector embeddings for the given text.""" - embedding = embed_model.encode(text) - return embedding.tolist() -``` - -### 步骤 5. 连接 TiDB 集群 - -使用 `TiDBVectorClient` 类连接你的 TiDB 集群,并创建一个包含向量列的 `embedded_documents` 表。 - -> **Note** -> -> 请确保表中向量列的维度与嵌入模型生成的向量维度一致。例如,**msmarco-MiniLM-L12-cos-v5** 模型生成的向量为 384 维,因此 `embedded_documents` 表中的向量列维度也应为 384。 - -```python -import os -from tidb_vector.integrations import TiDBVectorClient -from dotenv import load_dotenv - -# Load the connection string from the .env file -load_dotenv() - -vector_store = TiDBVectorClient( - # The 'embedded_documents' table will store the vector data. - table_name='embedded_documents', - # The connection string to the TiDB cluster. - connection_string=os.environ.get('TIDB_DATABASE_URL'), - # The dimension of the vector generated by the embedding model. - vector_dimension=embed_model_dims, - # Recreate the table if it already exists. - drop_existing_table=True, -) -``` - -### 步骤 6. 嵌入文本数据并存储向量 - -在此步骤中,你将准备包含单词的示例文档,如 "dog"、"fish" 和 "tree"。以下代码使用 `text_to_embedding()` 函数将这些文本文档转换为向量嵌入,并插入到向量存储中。 - -```python -documents = [ - { - "id": "f8e7dee2-63b6-42f1-8b60-2d46710c1971", - "text": "dog", - "embedding": text_to_embedding("dog"), - "metadata": {"category": "animal"}, - }, - { - "id": "8dde1fbc-2522-4ca2-aedf-5dcb2966d1c6", - "text": "fish", - "embedding": text_to_embedding("fish"), - "metadata": {"category": "animal"}, - }, - { - "id": "e4991349-d00b-485c-a481-f61695f2b5ae", - "text": "tree", - "embedding": text_to_embedding("tree"), - "metadata": {"category": "plant"}, - }, -] - -vector_store.insert( - ids=[doc["id"] for doc in documents], - texts=[doc["text"] for doc in documents], - embeddings=[doc["embedding"] for doc in documents], - metadatas=[doc["metadata"] for doc in documents], -) -``` - -### 步骤 7. 执行语义搜索 - -在此步骤中,你将搜索 "a swimming animal",该查询与现有文档中的单词并不直接匹配。 - -以下代码再次使用 `text_to_embedding()` 函数将查询文本转换为向量嵌入,并用该嵌入向量查询,返回最接近的前三个结果。 - -```python -def print_result(query, result): - print(f"Search result (\"{query}\"):") - for r in result: - print(f"- text: \"{r.document}\", distance: {r.distance}") - -query = "a swimming animal" -query_embedding = text_to_embedding(query) -search_result = vector_store.query(query_embedding, k=3) -print_result(query, search_result) -``` - -运行 `example.py` 文件,输出如下: - -```plain -Search result ("a swimming animal"): -- text: "fish", distance: 0.4562914811223072 -- text: "dog", distance: 0.6469335836410557 -- text: "tree", distance: 0.798545178640937 -``` - -搜索结果中的三个词根据与查询向量的距离排序:距离越小,`document` 越相关。 - -因此,根据输出,最有可能的游泳动物是 fish,或者是一只擅长游泳的 dog。 - -## 相关阅读 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) \ No newline at end of file diff --git a/vector-search/vector-search-get-started-using-sql.md b/vector-search/vector-search-get-started-using-sql.md deleted file mode 100644 index 4c8480a128dba..0000000000000 --- a/vector-search/vector-search-get-started-using-sql.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: 通过 SQL 快速入门向量检索 -summary: 学习如何仅使用 SQL 语句在 TiDB 中快速开始向量检索,为你的生成式 AI 应用提供支持。 ---- - -# 通过 SQL 快速入门向量检索 - -TiDB 扩展了 MySQL 语法以支持 [向量检索](/vector-search/vector-search-overview.md),并引入了新的 [向量数据类型](/vector-search/vector-search-data-types.md) 以及若干 [向量函数](/vector-search/vector-search-functions-and-operators.md)。 - -本教程演示了如何仅使用 SQL 语句在 TiDB 中快速开始向量检索。你将学习如何使用 [MySQL 命令行客户端](https://dev.mysql.com/doc/refman/8.4/en/mysql.html) 完成以下操作: - -- 连接到你的 TiDB 集群。 -- 创建向量表。 -- 存储向量嵌入。 -- 执行向量检索查询。 - - - -> **Warning:** -> -> 向量检索功能为实验性特性。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能处于 beta 阶段,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 前置条件 - -完成本教程,你需要: - -- 在本地安装 [MySQL 命令行客户端](https://dev.mysql.com/doc/refman/8.4/en/mysql.html)(MySQL CLI)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 快速开始 - -### 第 1 步:连接到 TiDB 集群 - -根据你选择的 TiDB 部署方式,连接到你的 TiDB 集群。 - - -
- -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,然后点击目标集群名称进入其概览页面。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 在连接对话框中,从 **Connect With** 下拉列表中选择 **MySQL CLI**,并保持 **Connection Type** 的默认设置为 **Public**。 - -4. 如果你还未设置密码,点击 **Generate Password** 生成一个随机密码。 - -5. 复制连接命令并粘贴到你的终端中。以下是 macOS 的示例: - - ```bash - mysql -u '.root' -h '' -P 4000 -D 'test' --ssl-mode=VERIFY_IDENTITY --ssl-ca=/etc/ssl/cert.pem -p'' - ``` - -
-
- -当你的 TiDB 自建集群启动后,在终端执行集群连接命令。 - -以下是 macOS 的示例连接命令: - -```bash -mysql --comments --host 127.0.0.1 --port 4000 -u root -``` - -
- -
- -### 第 2 步:创建向量表 - -在创建表时,你可以通过指定 `VECTOR` 数据类型,将某一列定义为 [向量](/vector-search/vector-search-overview.md#vector-embedding) 列。 - -例如,若要创建一个包含三维 `VECTOR` 列的 `embedded_documents` 表,可在 MySQL CLI 中执行如下 SQL 语句: - -```sql -USE test; -CREATE TABLE embedded_documents ( - id INT PRIMARY KEY, - -- Column to store the original content of the document. - document TEXT, - -- Column to store the vector representation of the document. - embedding VECTOR(3) -); -``` - -预期输出如下: - -```text -Query OK, 0 rows affected (0.27 sec) -``` - -### 第 3 步:向表中插入向量嵌入 - -向 `embedded_documents` 表中插入三条带有 [向量嵌入](/vector-search/vector-search-overview.md#vector-embedding) 的文档: - -```sql -INSERT INTO embedded_documents -VALUES - (1, 'dog', '[1,2,1]'), - (2, 'fish', '[1,2,4]'), - (3, 'tree', '[1,0,0]'); -``` - -预期输出如下: - -``` -Query OK, 3 rows affected (0.15 sec) -Records: 3 Duplicates: 0 Warnings: 0 -``` - -> **Note** -> -> 本示例简化了向量嵌入的维度,仅使用 3 维向量进行演示。 -> -> 在实际应用中,[嵌入模型](/vector-search/vector-search-overview.md#embedding-model) 通常会生成数百或数千维的向量嵌入。 - -### 第 4 步:查询向量表 - -为验证文档是否已正确插入,可查询 `embedded_documents` 表: - -```sql -SELECT * FROM embedded_documents; -``` - -预期输出如下: - -```sql -+----+----------+-----------+ -| id | document | embedding | -+----+----------+-----------+ -| 1 | dog | [1,2,1] | -| 2 | fish | [1,2,4] | -| 3 | tree | [1,0,0] | -+----+----------+-----------+ -3 rows in set (0.15 sec) -``` - -### 第 5 步:执行向量检索查询 - -与全文检索类似,用户在使用向量检索时会向应用提供检索词。 - -在本示例中,检索词为 “a swimming animal”,其对应的向量嵌入假定为 `[1,2,3]`。在实际应用中,你需要使用嵌入模型将用户的检索词转换为向量嵌入。 - -执行如下 SQL 语句,TiDB 会通过计算并排序表中向量嵌入与 `[1,2,3]` 之间的余弦距离(`vec_cosine_distance`),找出与该向量最接近的前三个文档。 - -```sql -SELECT id, document, vec_cosine_distance(embedding, '[1,2,3]') AS distance -FROM embedded_documents -ORDER BY distance -LIMIT 3; -``` - -预期输出如下: - -```plain -+----+----------+---------------------+ -| id | document | distance | -+----+----------+---------------------+ -| 2 | fish | 0.00853986601633272 | -| 1 | dog | 0.12712843905603044 | -| 3 | tree | 0.7327387580875756 | -+----+----------+---------------------+ -3 rows in set (0.15 sec) -``` - -检索结果中的三个词条按照与查询向量的距离升序排列:距离越小,`document` 与检索向量的相关性越高。 - -因此,根据输出,最有可能的“swimming animal”是 fish,其次可能是会游泳的 dog。 - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-improve-performance.md b/vector-search/vector-search-improve-performance.md deleted file mode 100644 index 222f648d95947..0000000000000 --- a/vector-search/vector-search-improve-performance.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: 提升向量检索性能 -summary: 了解提升 TiDB 向量检索性能的最佳实践。 ---- - -# 提升向量检索性能 - -TiDB 向量检索支持执行近似最近邻(ANN)查询,用于查找与图片、文档或其他输入相似的结果。为了提升查询性能,请参考以下最佳实践。 - - - -> **Warning:** -> -> 向量检索功能为实验性特性。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能处于 beta 阶段,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 及以上(推荐 v8.5.0 及以上)。 - -## 为向量列添加向量检索索引 - -[向量检索索引](/vector-search/vector-search-index.md) 能显著提升向量检索查询的性能,通常可提升 10 倍以上,代价仅为召回率的轻微下降。 - -## 确保向量索引已完全构建 - -在你插入大量向量数据后,部分数据可能仍处于 Delta 层,等待持久化。这部分数据的向量索引会在数据持久化后构建。在所有向量数据都被索引之前,向量检索的性能并不理想。要查看索引的构建进度,请参见 [查看索引构建进度](/vector-search/vector-search-index.md#view-index-build-progress)。 - -## 降低向量维度或缩短嵌入向量 - -随着向量维度的增加,向量检索索引和查询的计算复杂度会显著提升,需要进行更多的浮点数比较。 - -为了优化性能,建议在可行的情况下降低向量维度。这通常需要切换到其他嵌入模型。在切换模型时,你需要评估模型变更对向量查询准确率的影响。 - -某些嵌入模型(如 OpenAI 的 `text-embedding-3-large`)支持[缩短嵌入向量](https://openai.com/index/new-embedding-models-and-api-updates/),即在不影响嵌入向量语义表达能力的前提下,从向量序列末尾移除部分数值。你也可以通过此类嵌入模型来降低向量维度。 - -## 查询结果中排除向量列 - -向量嵌入数据通常体积较大,仅在检索过程中使用。通过在查询结果中排除向量列,可以大幅减少 TiDB 服务器与 SQL 客户端之间传输的数据量,从而提升查询性能。 - -要排除向量列,请在 `SELECT` 子句中显式列出你需要查询的字段,而不是使用 `SELECT *` 查询所有列。 - -## 预热索引 - -当访问从未被使用过或长时间未被访问(冷访问)的索引时,TiDB 需要从云存储或磁盘(而非内存)加载整个索引。此过程会耗费一定时间,通常导致查询延迟升高。此外,如果长时间(如数小时)没有 SQL 查询,计算资源会被回收,后续访问也会变为冷访问。 - -为避免此类查询延迟,在实际负载前,可以通过执行命中向量索引的类似向量检索查询来预热索引。 \ No newline at end of file diff --git a/vector-search/vector-search-index.md b/vector-search/vector-search-index.md deleted file mode 100644 index eca0498eeaa34..0000000000000 --- a/vector-search/vector-search-index.md +++ /dev/null @@ -1,273 +0,0 @@ ---- -title: 向量检索索引 -summary: 了解如何构建和使用向量检索索引,以加速 TiDB 中的 K-最近邻(KNN)查询。 ---- - -# 向量检索索引 - -如 [向量检索](/vector-search/vector-search-overview.md) 文档所述,向量检索通过计算给定向量与数据库中所有向量之间的距离,找出 Top K-最近邻(KNN)。这种方式能够提供准确的结果,但当表中包含大量向量时,由于需要全表扫描,查询速度会很慢。[^1] - -为了提升检索效率,你可以在 TiDB 中为近似 KNN(ANN)检索创建向量检索索引。使用向量索引进行向量检索时,TiDB 可以大幅提升查询性能,仅以极小的准确率损失为代价,通常能保持 90% 以上的检索召回率。 - - - -> **Warning:** -> -> 向量检索功能为实验性特性。不建议在生产环境中使用。该功能可能会在未提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能处于 beta 阶段,可能会在未提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 及以上(推荐 v8.5.0 及以上)。 - -目前,TiDB 支持 [HNSW(Hierarchical Navigable Small World)](https://en.wikipedia.org/wiki/Hierarchical_navigable_small_world) 向量检索索引算法。 - -## 限制 - -- 集群中必须提前部署 TiFlash 节点。 -- 向量检索索引不能作为主键或唯一索引使用。 -- 向量检索索引只能创建在单个向量列上,不能与其他列(如整数或字符串)组合为复合索引。 -- 创建和使用向量检索索引时,必须指定距离函数。目前仅支持余弦距离 `VEC_COSINE_DISTANCE()` 和 L2 距离 `VEC_L2_DISTANCE()`。 -- 对于同一列,不支持使用相同距离函数创建多个向量检索索引。 -- 不支持直接删除带有向量检索索引的列。你可以先删除该列上的向量检索索引,再删除该列。 -- 不支持修改带有向量索引的列的数据类型。 -- 不支持将向量检索索引设置为 [不可见](/sql-statements/sql-statement-alter-index.md)。 -- 不支持在启用[静态加密](https://docs.pingcap.com/tidb/stable/encryption-at-rest)的 TiFlash 节点上构建向量检索索引。 - -## 创建 HNSW 向量索引 - -[HNSW](https://en.wikipedia.org/wiki/Hierarchical_navigable_small_world) 是最流行的向量索引算法之一。HNSW 索引在性能和准确率之间有很好的平衡,在特定场景下准确率可达 98%。 - -在 TiDB 中,你可以通过以下任一方式为具有 [向量数据类型](/vector-search/vector-search-data-types.md) 的列创建 HNSW 索引: - -- 创建表时,使用如下语法为向量列指定 HNSW 索引: - - ```sql - CREATE TABLE foo ( - id INT PRIMARY KEY, - embedding VECTOR(5), - VECTOR INDEX idx_embedding ((VEC_COSINE_DISTANCE(embedding))) - ); - ``` - -- 对于已存在且包含向量列的表,使用如下语法为该向量列创建 HNSW 索引: - - ```sql - CREATE VECTOR INDEX idx_embedding ON foo ((VEC_COSINE_DISTANCE(embedding))); - ALTER TABLE foo ADD VECTOR INDEX idx_embedding ((VEC_COSINE_DISTANCE(embedding))); - - -- 你也可以显式指定 "USING HNSW" 来构建向量检索索引。 - CREATE VECTOR INDEX idx_embedding ON foo ((VEC_COSINE_DISTANCE(embedding))) USING HNSW; - ALTER TABLE foo ADD VECTOR INDEX idx_embedding ((VEC_COSINE_DISTANCE(embedding))) USING HNSW; - ``` - -> **Note:** -> -> 向量检索索引功能依赖于表的 TiFlash 副本。 -> -> - 如果在建表时定义了向量检索索引,TiDB 会自动为该表创建 TiFlash 副本。 -> - 如果建表时未定义向量检索索引,且当前表没有 TiFlash 副本,则需要在为表添加向量检索索引前,手动创建 TiFlash 副本。例如:`ALTER TABLE 'table_name' SET TIFLASH REPLICA 1;`。 - -创建 HNSW 向量索引时,需要为向量指定距离函数: - -- 余弦距离:`((VEC_COSINE_DISTANCE(embedding)))` -- L2 距离:`((VEC_L2_DISTANCE(embedding)))` - -向量索引只能创建在定长向量列上,例如定义为 `VECTOR(3)` 的列。不能为非定长向量列(如定义为 `VECTOR` 的列)创建索引,因为只有相同维度的向量之间才能计算距离。 - -关于向量检索索引的限制,参见 [限制](#限制)。 - -## 使用向量索引 - -在 K-最近邻检索查询中,可以通过如下 `ORDER BY ... LIMIT` 语句使用向量检索索引: - -```sql -SELECT * -FROM foo -ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3, 4, 5]') -LIMIT 10 -``` - -要在向量检索中使用索引,确保 `ORDER BY ... LIMIT` 子句使用的距离函数与创建向量索引时指定的距离函数一致。 - -## 向量索引与过滤条件的配合使用 - -包含预过滤(使用 `WHERE` 子句)的查询无法利用向量索引,因为根据 SQL 语义,这类查询并不是在查找 K-最近邻。例如: - -```sql --- 对于如下查询,`WHERE` 过滤在 KNN 之前执行,因此无法使用向量索引: - -SELECT * FROM vec_table -WHERE category = "document" -ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3]') -LIMIT 5; -``` - -要在带有过滤条件的场景下使用向量索引,可以先通过向量检索查找 K-最近邻,再进行结果过滤: - -```sql --- 对于如下查询,`WHERE` 过滤在 KNN 之后执行,因此无法使用向量索引: - -SELECT * FROM -( - SELECT * FROM vec_table - ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3]') - LIMIT 5 -) t -WHERE category = "document"; - --- 注意,如果部分结果被过滤,最终返回的结果可能少于 5 条。 -``` - -## 查看索引构建进度 - -在你插入大量数据后,部分数据可能不会立即持久化到 TiFlash。对于已持久化的向量数据,向量检索索引会同步构建。对于尚未持久化的数据,索引会在数据持久化后再构建。该过程不会影响数据的准确性和一致性,你可以随时进行向量检索并获得完整结果。但在向量索引完全构建前,性能会较差。 - -你可以通过查询 `INFORMATION_SCHEMA.TIFLASH_INDEXES` 表来查看索引构建进度: - -```sql -SELECT * FROM INFORMATION_SCHEMA.TIFLASH_INDEXES; -+---------------+------------+----------+-------------+---------------+-----------+----------+------------+---------------------+-------------------------+--------------------+------------------------+---------------+------------------+ -| TIDB_DATABASE | TIDB_TABLE | TABLE_ID | COLUMN_NAME | INDEX_NAME | COLUMN_ID | INDEX_ID | INDEX_KIND | ROWS_STABLE_INDEXED | ROWS_STABLE_NOT_INDEXED | ROWS_DELTA_INDEXED | ROWS_DELTA_NOT_INDEXED | ERROR_MESSAGE | TIFLASH_INSTANCE | -+---------------+------------+----------+-------------+---------------+-----------+----------+------------+---------------------+-------------------------+--------------------+------------------------+---------------+------------------+ -| test | tcff1d827 | 219 | col1fff | 0a452311 | 7 | 1 | HNSW | 29646 | 0 | 0 | 0 | | 127.0.0.1:3930 | -| test | foo | 717 | embedding | idx_embedding | 2 | 1 | HNSW | 0 | 0 | 0 | 3 | | 127.0.0.1:3930 | -+---------------+------------+----------+-------------+---------------+-----------+----------+------------+---------------------+-------------------------+--------------------+------------------------+---------------+------------------+ -``` - -- 你可以通过 `ROWS_STABLE_INDEXED` 和 `ROWS_STABLE_NOT_INDEXED` 列查看索引构建进度。当 `ROWS_STABLE_NOT_INDEXED` 为 0 时,索引构建完成。 - - 作为参考,索引一个 500 MiB、768 维的向量数据集可能需要 20 分钟。索引器可以并行为多个表构建索引。目前不支持调整索引器优先级或速度。 - -- 你可以通过 `ROWS_DELTA_NOT_INDEXED` 列查看 Delta 层中的行数。TiFlash 的存储层分为 Delta 层和 Stable 层。Delta 层存储最近插入或更新的行,并会根据写入负载定期合并到 Stable 层。该合并过程称为 Compaction。 - - Delta 层始终不会被索引。为获得最佳性能,你可以强制将 Delta 层合并到 Stable 层,从而使所有数据都能被索引: - - ```sql - ALTER TABLE COMPACT; - ``` - - 更多信息,参见 [`ALTER TABLE ... COMPACT`](/sql-statements/sql-statement-alter-table-compact.md)。 - -此外,你还可以通过执行 `ADMIN SHOW DDL JOBS;` 并查看 `row count` 字段来监控 DDL 任务的执行进度。但该方法并不完全准确,因为 `row count` 的值来自 `TIFLASH_INDEXES` 表中的 `rows_stable_indexed` 字段。你可以将此方法作为索引进度的参考。 - -## 检查是否使用了向量索引 - -可以使用 [`EXPLAIN`](/sql-statements/sql-statement-explain.md) 或 [`EXPLAIN ANALYZE`](/sql-statements/sql-statement-explain-analyze.md) 语句检查查询是否使用了向量索引。当 `TableFullScan` 执行器的 `operator info` 列中出现 `annIndex:` 时,表示该表扫描正在利用向量索引。 - -**示例:已使用向量索引** - -```sql -[tidb]> EXPLAIN SELECT * FROM vector_table_with_index -ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3]') -LIMIT 10; -+-----+-------------------------------------------------------------------------------------+ -| ... | operator info | -+-----+-------------------------------------------------------------------------------------+ -| ... | ... | -| ... | Column#5, offset:0, count:10 | -| ... | ..., vec_cosine_distance(test.vector_table_with_index.embedding, [1,2,3])->Column#5 | -| ... | MppVersion: 1, data:ExchangeSender_16 | -| ... | ExchangeType: PassThrough | -| ... | ... | -| ... | Column#4, offset:0, count:10 | -| ... | ..., vec_cosine_distance(test.vector_table_with_index.embedding, [1,2,3])->Column#4 | -| ... | annIndex:COSINE(test.vector_table_with_index.embedding..[1,2,3], limit:10), ... | -+-----+-------------------------------------------------------------------------------------+ -9 rows in set (0.01 sec) -``` - -**示例:未使用向量索引(未指定 Top K)** - -```sql -[tidb]> EXPLAIN SELECT * FROM vector_table_with_index - -> ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3]'); -+--------------------------------+-----+--------------------------------------------------+ -| id | ... | operator info | -+--------------------------------+-----+--------------------------------------------------+ -| Projection_15 | ... | ... | -| └─Sort_4 | ... | Column#4 | -| └─Projection_16 | ... | ..., vec_cosine_distance(..., [1,2,3])->Column#4 | -| └─TableReader_14 | ... | MppVersion: 1, data:ExchangeSender_13 | -| └─ExchangeSender_13 | ... | ExchangeType: PassThrough | -| └─TableFullScan_12 | ... | keep order:false, stats:pseudo | -+--------------------------------+-----+--------------------------------------------------+ -6 rows in set, 1 warning (0.01 sec) -``` - -当无法使用向量索引时,部分场景下会出现警告,帮助你了解原因: - -```sql --- 使用了错误的距离函数: -[tidb]> EXPLAIN SELECT * FROM vector_table_with_index -ORDER BY VEC_L2_DISTANCE(embedding, '[1, 2, 3]') -LIMIT 10; - -[tidb]> SHOW WARNINGS; -ANN index not used: not ordering by COSINE distance - --- 使用了错误的排序方式: -[tidb]> EXPLAIN SELECT * FROM vector_table_with_index -ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3]') DESC -LIMIT 10; - -[tidb]> SHOW WARNINGS; -ANN index not used: index can be used only when ordering by vec_cosine_distance() in ASC order -``` - -## 分析向量检索性能 - -要了解向量索引的详细使用信息,可以执行 [`EXPLAIN ANALYZE`](/sql-statements/sql-statement-explain-analyze.md) 语句,并查看输出中的 `execution info` 列: - -```sql -[tidb]> EXPLAIN ANALYZE SELECT * FROM vector_table_with_index -ORDER BY VEC_COSINE_DISTANCE(embedding, '[1, 2, 3]') -LIMIT 10; -+-----+--------------------------------------------------------+-----+ -| | execution info | | -+-----+--------------------------------------------------------+-----+ -| ... | time:339.1ms, loops:2, RU:0.000000, Concurrency:OFF | ... | -| ... | time:339ms, loops:2 | ... | -| ... | time:339ms, loops:3, Concurrency:OFF | ... | -| ... | time:339ms, loops:3, cop_task: {...} | ... | -| ... | tiflash_task:{time:327.5ms, loops:1, threads:4} | ... | -| ... | tiflash_task:{time:327.5ms, loops:1, threads:4} | ... | -| ... | tiflash_task:{time:327.5ms, loops:1, threads:4} | ... | -| ... | tiflash_task:{time:327.5ms, loops:1, threads:4} | ... | -| ... | tiflash_task:{...}, vector_idx:{ | ... | -| | load:{total:68ms,from_s3:1,from_disk:0,from_cache:0},| | -| | search:{total:0ms,visited_nodes:2,discarded_nodes:0},| | -| | read:{vec_total:0ms,others_total:0ms}},...} | | -+-----+--------------------------------------------------------+-----+ -``` - -> **Note:** -> -> 执行信息为内部字段,字段及格式可能随时变更,无需依赖。 - -部分重要字段说明: - -- `vector_index.load.total`:索引加载总耗时。该字段可能大于实际查询耗时,因为可能有多个向量索引并行加载。 -- `vector_index.load.from_s3`:从 S3 加载的索引数量。 -- `vector_index.load.from_disk`:从磁盘加载的索引数量。该索引此前已从 S3 下载到本地磁盘。 -- `vector_index.load.from_cache`:从缓存加载的索引数量。该索引此前已从 S3 下载到本地缓存。 -- `vector_index.search.total`:索引内检索总耗时。较大的延迟通常意味着索引为冷数据(从未访问或长时间未访问),导致检索时有大量 I/O 操作。该字段可能大于实际查询耗时,因为可能有多个向量索引并行检索。 -- `vector_index.search.discarded_nodes`:检索过程中访问但被丢弃的向量行数。这些被丢弃的向量不会计入检索结果。较大的值通常表示由于 `UPDATE` 或 `DELETE` 语句导致存在大量过期行。 - -关于输出的解读,参见 [`EXPLAIN`](/sql-statements/sql-statement-explain.md)、[`EXPLAIN ANALYZE`](/sql-statements/sql-statement-explain-analyze.md) 及 [EXPLAIN Walkthrough](/explain-walkthrough.md)。 - -## 参见 - -- [提升向量检索性能](/vector-search/vector-search-improve-performance.md) -- [向量数据类型](/vector-search/vector-search-data-types.md) - -[^1]: KNN 检索的解释改编自 ClickHouse 文档中由 [rschu1ze](https://github.com/rschu1ze) 撰写的 [Approximate Nearest Neighbor Search Indexes](https://github.com/ClickHouse/ClickHouse/pull/50661/files#diff-7ebd9e71df96e74230c9a7e604fa7cb443be69ba5e23bf733fcecd4cc51b7576) 文档,遵循 Apache License 2.0 许可协议。 \ No newline at end of file diff --git a/vector-search/vector-search-integrate-with-django-orm.md b/vector-search/vector-search-integrate-with-django-orm.md deleted file mode 100644 index 0efdd591d4e5e..0000000000000 --- a/vector-search/vector-search-integrate-with-django-orm.md +++ /dev/null @@ -1,288 +0,0 @@ ---- -title: 将 TiDB 向量检索集成到 Django ORM -summary: 学习如何将 TiDB 向量检索集成到 Django ORM,用于存储嵌入向量并执行语义检索。 ---- - -# 将 TiDB 向量检索集成到 Django ORM - -本教程将指导你如何使用 [Django](https://www.djangoproject.com/) ORM 与 [TiDB 向量检索](/vector-search/vector-search-overview.md) 进行交互,存储嵌入向量,并执行向量检索查询。 - - - -> **Warning:** -> -> 向量检索功能为实验性特性。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能处于 beta 阶段,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 运行示例应用 - -你可以按照以下步骤快速了解如何将 TiDB 向量检索集成到 Django ORM。 - -### 步骤 1. 克隆代码仓库 - -将 `tidb-vector-python` 仓库克隆到本地: - -```shell -git clone https://github.com/pingcap/tidb-vector-python.git -``` - -### 步骤 2. 创建虚拟环境 - -为你的项目创建一个虚拟环境: - -```bash -cd tidb-vector-python/examples/orm-django-quickstart -python3 -m venv .venv -source .venv/bin/activate -``` - -### 步骤 3. 安装所需依赖 - -为示例项目安装所需依赖: - -```bash -pip install -r requirements.txt -``` - -或者,你也可以为你的项目单独安装以下包: - -```bash -pip install Django django-tidb mysqlclient numpy python-dotenv -``` - -如果在安装 mysqlclient 时遇到问题,请参考 mysqlclient 官方文档。 - -#### 什么是 `django-tidb` - -`django-tidb` 是 Django 的 TiDB 方言,增强了 Django ORM 对 TiDB 特性的支持(如向量检索),并解决了 TiDB 与 Django 之间的兼容性问题。 - -安装 `django-tidb` 时,请选择与你的 Django 版本相匹配的版本。例如,如果你使用的是 `django==4.2.*`,则安装 `django-tidb==4.2.*`。小版本号无需完全一致,建议使用最新的小版本。 - -更多信息请参考 [django-tidb 仓库](https://github.com/pingcap/django-tidb)。 - -### 步骤 4. 配置环境变量 - -根据你选择的 TiDB 部署方式配置环境变量。 - - -
- -对于 TiDB Cloud Starter 集群,请按以下步骤获取集群连接串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确认连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public` - - **Branch** 设置为 `main` - - **Connect With** 设置为 `General` - - **Operating System** 与你的环境一致 - - > **Tip:** - > - > 如果你的程序运行在 Windows Subsystem for Linux (WSL) 中,请切换到对应的 Linux 发行版。 - -4. 从连接对话框中复制连接参数。 - - > **Tip:** - > - > 如果你还未设置密码,可点击 **Generate Password** 生成随机密码。 - -5. 在你的 Python 项目根目录下创建 `.env` 文件,并将连接参数粘贴到对应的环境变量中。 - - - `TIDB_HOST`:TiDB 集群的主机地址 - - `TIDB_PORT`:TiDB 集群的端口 - - `TIDB_USERNAME`:连接 TiDB 集群的用户名 - - `TIDB_PASSWORD`:连接 TiDB 集群的密码 - - `TIDB_DATABASE`:要连接的数据库名 - - `TIDB_CA_PATH`:根证书文件的路径 - - 以下是 macOS 的示例: - - ```dotenv - TIDB_HOST=gateway01.****.prod.aws.tidbcloud.com - TIDB_PORT=4000 - TIDB_USERNAME=********.root - TIDB_PASSWORD=******** - TIDB_DATABASE=test - TIDB_CA_PATH=/etc/ssl/cert.pem - ``` - -
-
- -对于 TiDB 自建版集群,在你的 Python 项目根目录下创建 `.env` 文件。将以下内容复制到 `.env` 文件中,并根据你的 TiDB 集群连接参数修改环境变量的值: - -```dotenv -TIDB_HOST=127.0.0.1 -TIDB_PORT=4000 -TIDB_USERNAME=root -TIDB_PASSWORD= -TIDB_DATABASE=test -``` - -如果你在本地运行 TiDB,`TIDB_HOST` 默认为 `127.0.0.1`。初始的 `TIDB_PASSWORD` 为空,如果是首次启动集群,可以省略该字段。 - -各参数说明如下: - -- `TIDB_HOST`:TiDB 集群的主机地址 -- `TIDB_PORT`:TiDB 集群的端口 -- `TIDB_USERNAME`:连接 TiDB 集群的用户名 -- `TIDB_PASSWORD`:连接 TiDB 集群的密码 -- `TIDB_DATABASE`:要连接的数据库名 - -
- -
- -### 步骤 5. 运行示例 - -迁移数据库结构: - -```bash -python manage.py migrate -``` - -运行 Django 开发服务器: - -```bash -python manage.py runserver -``` - -在浏览器中访问 `http://127.0.0.1:8000` 体验示例应用。可用的 API 路径如下: - -| API Path | Description | -| --------------------------------------- | ---------------------------------------- | -| `POST: /insert_documents` | 插入带有嵌入向量的文档。 | -| `GET: /get_nearest_neighbors_documents` | 获取 3 个最近邻文档。 | -| `GET: /get_documents_within_distance` | 获取距离在指定范围内的文档。 | - -## 示例代码片段 - -你可以参考以下示例代码片段,完成你自己的应用开发。 - -### 连接 TiDB 集群 - -在 `sample_project/settings.py` 文件中添加如下配置: - -```python -dotenv.load_dotenv() - -DATABASES = { - "default": { - # https://github.com/pingcap/django-tidb - "ENGINE": "django_tidb", - "HOST": os.environ.get("TIDB_HOST", "127.0.0.1"), - "PORT": int(os.environ.get("TIDB_PORT", 4000)), - "USER": os.environ.get("TIDB_USERNAME", "root"), - "PASSWORD": os.environ.get("TIDB_PASSWORD", ""), - "NAME": os.environ.get("TIDB_DATABASE", "test"), - "OPTIONS": { - "charset": "utf8mb4", - }, - } -} - -TIDB_CA_PATH = os.environ.get("TIDB_CA_PATH", "") -if TIDB_CA_PATH: - DATABASES["default"]["OPTIONS"]["ssl_mode"] = "VERIFY_IDENTITY" - DATABASES["default"]["OPTIONS"]["ssl"] = { - "ca": TIDB_CA_PATH, - } -``` - -你可以在项目根目录下创建 `.env` 文件,并将 `TIDB_HOST`、`TIDB_PORT`、`TIDB_USERNAME`、`TIDB_PASSWORD`、`TIDB_DATABASE` 和 `TIDB_CA_PATH` 等环境变量设置为你实际的 TiDB 集群参数。 - -### 创建向量表 - -#### 定义向量列 - -`tidb-django` 提供了 `VectorField` 用于在表中存储向量嵌入。 - -创建一个包含名为 `embedding` 的 3 维向量列的表。 - -```python -class Document(models.Model): - content = models.TextField() - embedding = VectorField(dimensions=3) -``` - -### 存储带嵌入向量的文档 - -```python -Document.objects.create(content="dog", embedding=[1, 2, 1]) -Document.objects.create(content="fish", embedding=[1, 2, 4]) -Document.objects.create(content="tree", embedding=[1, 0, 0]) -``` - -### 检索最近邻文档 - -TiDB 向量检索支持以下距离函数: - -- `L1Distance` -- `L2Distance` -- `CosineDistance` -- `NegativeInnerProduct` - -基于余弦距离函数,检索与查询向量 `[1, 2, 3]` 语义最接近的前 3 个文档。 - -```python -results = Document.objects.annotate( - distance=CosineDistance('embedding', [1, 2, 3]) -).order_by('distance')[:3] -``` - -### 检索距离在指定范围内的文档 - -检索与查询向量 `[1, 2, 3]` 余弦距离小于 0.2 的文档。 - -```python -results = Document.objects.annotate( - distance=CosineDistance('embedding', [1, 2, 3]) -).filter(distance__lt=0.2).order_by('distance')[:3] -``` - -## 相关文档 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-integrate-with-jinaai-embedding.md b/vector-search/vector-search-integrate-with-jinaai-embedding.md deleted file mode 100644 index 9d022b767934d..0000000000000 --- a/vector-search/vector-search-integrate-with-jinaai-embedding.md +++ /dev/null @@ -1,303 +0,0 @@ ---- -title: 集成 TiDB 向量检索与 Jina AI Embeddings API -summary: 学习如何将 TiDB 向量检索与 Jina AI Embeddings API 集成,实现向量存储与语义检索。 ---- - -# 集成 TiDB 向量检索与 Jina AI Embeddings API - -本教程将指导你如何使用 [Jina AI](https://jina.ai/) 为文本数据生成向量,并将这些向量存储到 TiDB 向量存储中,基于向量实现相似文本的检索。 - - - -> **Warning:** -> -> 向量检索功能目前为实验性特性。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能目前为 Beta 版本,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB Self-Managed、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB Self-Managed 和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 运行示例应用 - -你可以按照以下步骤,快速了解如何将 TiDB 向量检索与 JinaAI Embedding 集成。 - -### 步骤 1. 克隆代码仓库 - -将 `tidb-vector-python` 仓库克隆到本地: - -```shell -git clone https://github.com/pingcap/tidb-vector-python.git -``` - -### 步骤 2. 创建虚拟环境 - -为你的项目创建一个虚拟环境: - -```bash -cd tidb-vector-python/examples/jina-ai-embeddings-demo -python3 -m venv .venv -source .venv/bin/activate -``` - -### 步骤 3. 安装依赖 - -为示例项目安装所需依赖: - -```bash -pip install -r requirements.txt -``` - -### 步骤 4. 配置环境变量 - -从 [Jina AI Embeddings API](https://jina.ai/embeddings/) 页面获取 Jina AI API key,然后根据你选择的 TiDB 部署方式配置环境变量。 - - -
- -对于 TiDB Cloud Starter 集群,按如下步骤获取集群连接串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确认连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public` - - **Branch** 设置为 `main` - - **Connect With** 设置为 `SQLAlchemy` - - **Operating System** 与你的环境一致 - - > **Tip:** - > - > 如果你的程序运行在 Windows Subsystem for Linux (WSL) 中,请切换到对应的 Linux 发行版。 - -4. 切换到 **PyMySQL** 标签页,点击 **Copy** 图标复制连接串。 - - > **Tip:** - > - > 如果你还未设置密码,请点击 **Create password** 生成随机密码。 - -5. 在终端中将 Jina AI API key 和 TiDB 连接串设置为环境变量,或创建一个 `.env` 文件,内容如下: - - ```dotenv - JINAAI_API_KEY="****" - TIDB_DATABASE_URL="{tidb_connection_string}" - ``` - - 以下是 macOS 下的连接串示例: - - ```dotenv - TIDB_DATABASE_URL="mysql+pymysql://.root:@gateway01..prod.aws.tidbcloud.com:4000/test?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" - ``` - -
-
- -对于 TiDB Self-Managed 集群,在终端中设置连接 TiDB 集群的环境变量: - -```shell -export JINA_API_KEY="****" -export TIDB_DATABASE_URL="mysql+pymysql://:@:/" -# 例如:export TIDB_DATABASE_URL="mysql+pymysql://root@127.0.0.1:4000/test" -``` - -你需要根据自己的 TiDB 集群替换上述命令中的参数。如果你在本地运行 TiDB,`` 默认为 `127.0.0.1`。初始 `` 为空,如果是首次启动集群,可以省略该字段。 - -各参数说明如下: - -- ``:连接 TiDB 集群的用户名 -- ``:连接 TiDB 集群的密码 -- ``:TiDB 集群的主机地址 -- ``:TiDB 集群的端口 -- ``:你要连接的数据库名称 - -
- -
- -### 步骤 5. 运行示例 - -```bash -python jina-ai-embeddings-demo.py -``` - -示例输出: - -```text -- Inserting Data to TiDB... - - Inserting: Jina AI offers best-in-class embeddings, reranker and prompt optimizer, enabling advanced multimodal AI. - - Inserting: TiDB is an open-source MySQL-compatible database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. -- List All Documents and Their Distances to the Query: - - distance: 0.3585317326132522 - content: Jina AI offers best-in-class embeddings, reranker and prompt optimizer, enabling advanced multimodal AI. - - distance: 0.10858102967720984 - content: TiDB is an open-source MySQL-compatible database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. -- The Most Relevant Document and Its Distance to the Query: - - distance: 0.10858102967720984 - content: TiDB is an open-source MySQL-compatible database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. -``` - -## 示例代码片段 - -### 从 Jina AI 获取向量 - -定义 `generate_embeddings` 辅助函数,调用 Jina AI embeddings API: - -```python -import os -import requests -import dotenv - -dotenv.load_dotenv() - -JINAAI_API_KEY = os.getenv('JINAAI_API_KEY') - -def generate_embeddings(text: str): - JINAAI_API_URL = 'https://api.jina.ai/v1/embeddings' - JINAAI_HEADERS = { - 'Content-Type': 'application/json', - 'Authorization': f'Bearer {JINAAI_API_KEY}' - } - JINAAI_REQUEST_DATA = { - 'input': [text], - 'model': 'jina-embeddings-v2-base-en' # with dimension 768. - } - response = requests.post(JINAAI_API_URL, headers=JINAAI_HEADERS, json=JINAAI_REQUEST_DATA) - return response.json()['data'][0]['embedding'] -``` - -### 连接 TiDB 集群 - -通过 SQLAlchemy 连接 TiDB 集群: - -```python -import os -import dotenv - -from tidb_vector.sqlalchemy import VectorType -from sqlalchemy.orm import Session, declarative_base - -dotenv.load_dotenv() - -TIDB_DATABASE_URL = os.getenv('TIDB_DATABASE_URL') -assert TIDB_DATABASE_URL is not None -engine = create_engine(url=TIDB_DATABASE_URL, pool_recycle=300) -``` - -### 定义向量表结构 - -创建名为 `jinaai_tidb_demo_documents` 的表,包含用于存储文本的 `content` 字段和用于存储向量的 `content_vec` 字段: - -```python -from sqlalchemy import Column, Integer, String, create_engine -from sqlalchemy.orm import declarative_base - -Base = declarative_base() - -class Document(Base): - __tablename__ = "jinaai_tidb_demo_documents" - - id = Column(Integer, primary_key=True) - content = Column(String(255), nullable=False) - content_vec = Column( - # DIMENSIONS is determined by the embedding model, - # for Jina AI's jina-embeddings-v2-base-en model it's 768. - VectorType(dim=768), - comment="hnsw(distance=cosine)" -``` - -> **Note:** -> -> - 向量字段的维度必须与嵌入模型生成的向量维度一致。 -> - 本示例中,`jina-embeddings-v2-base-en` 模型生成的向量维度为 `768`。 - -### 使用 Jina AI 生成向量并存储到 TiDB - -使用 Jina AI Embeddings API 为每条文本生成向量,并将其存储到 TiDB: - -```python -TEXTS = [ - 'Jina AI offers best-in-class embeddings, reranker and prompt optimizer, enabling advanced multimodal AI.', - 'TiDB is an open-source MySQL-compatible database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads.', -] -data = [] - -for text in TEXTS: - # Generate embeddings for the texts via Jina AI API. - embedding = generate_embeddings(text) - data.append({ - 'text': text, - 'embedding': embedding - }) - -with Session(engine) as session: - print('- Inserting Data to TiDB...') - for item in data: - print(f' - Inserting: {item["text"]}') - session.add(Document( - content=item['text'], - content_vec=item['embedding'] - )) - session.commit() -``` - -### 在 TiDB 中基于 Jina AI 向量进行语义检索 - -通过 Jina AI embeddings API 为查询文本生成向量,然后基于 **查询文本的向量** 与 **向量表中每条数据的向量** 的余弦距离,检索最相关的文档: - -```python -query = 'What is TiDB?' -# Generate the embedding for the query via Jina AI API. -query_embedding = generate_embeddings(query) - -with Session(engine) as session: - print('- The Most Relevant Document and Its Distance to the Query:') - doc, distance = session.query( - Document, - Document.content_vec.cosine_distance(query_embedding).label('distance') - ).order_by( - 'distance' - ).limit(1).first() - print(f' - distance: {distance}\n' - f' content: {doc.content}') -``` - -## 相关阅读 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-integrate-with-langchain.md b/vector-search/vector-search-integrate-with-langchain.md deleted file mode 100644 index 5eb9298481e66..0000000000000 --- a/vector-search/vector-search-integrate-with-langchain.md +++ /dev/null @@ -1,662 +0,0 @@ ---- -title: 将向量检索集成到 LangChain -summary: 学习如何将 TiDB 向量检索与 LangChain 集成。 ---- - -# 将向量检索集成到 LangChain - -本教程演示如何将 TiDB 的 [向量检索](/vector-search/vector-search-overview.md) 功能与 [LangChain](https://python.langchain.com/) 集成。 - - - -> **Warning:** -> -> 向量检索功能为实验性功能。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能处于 beta 阶段,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 及以上(推荐 v8.5.0 及以上)。 - -> **Tip** -> -> 你可以在 Jupyter Notebook 查看完整的 [示例代码](https://github.com/langchain-ai/langchain/blob/master/docs/docs/integrations/vectorstores/tidb_vector.ipynb),或直接在 [Colab](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/integrations/vectorstores/tidb_vector.ipynb) 在线环境中运行示例代码。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Jupyter Notebook](https://jupyter.org/install)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 快速开始 - -本节将逐步指导你如何将 TiDB 向量检索与 LangChain 集成,实现语义检索。 - -### 步骤 1. 新建 Jupyter Notebook 文件 - -在你喜欢的目录下,新建一个名为 `integrate_with_langchain.ipynb` 的 Jupyter Notebook 文件: - -```shell -touch integrate_with_langchain.ipynb -``` - -### 步骤 2. 安装所需依赖 - -在你的项目目录下,运行以下命令安装所需的依赖包: - -```shell -!pip install langchain langchain-community -!pip install langchain-openai -!pip install pymysql -!pip install tidb-vector -``` - -在 Jupyter Notebook 中打开 `integrate_with_langchain.ipynb` 文件,并添加以下代码以导入所需包: - -```python -from langchain_community.document_loaders import TextLoader -from langchain_community.vectorstores import TiDBVectorStore -from langchain_openai import OpenAIEmbeddings -from langchain_text_splitters import CharacterTextSplitter -``` - -### 步骤 3. 配置环境 - -根据你选择的 TiDB 部署方式,配置环境变量。 - - -
- -对于 TiDB Cloud Starter 集群,按以下步骤获取集群连接串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确认连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 选择 `Public`。 - - **Branch** 选择 `main`。 - - **Connect With** 选择 `SQLAlchemy`。 - - **Operating System** 与你的环境一致。 - -4. 点击 **PyMySQL** 标签页,复制连接串。 - - > **Tip:** - > - > 如果你还未设置密码,可点击 **Generate Password** 生成随机密码。 - -5. 配置环境变量。 - - 本文档以 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型提供方为例。在此步骤中,你需要提供上一步获取的连接串和你的 [OpenAI API key](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)。 - - 运行以下代码配置环境变量。你将被提示输入连接串和 OpenAI API key: - - ```python - # 使用 getpass 在终端安全地输入环境变量。 - import getpass - import os - - # 从 TiDB Cloud 控制台复制你的连接串。 - # 连接串格式: "mysql+pymysql://:@:4000/?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" - tidb_connection_string = getpass.getpass("TiDB Connection String:") - os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") - ``` - -
-
- -本文档以 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型提供方为例。在此步骤中,你需要提供上一步获取的连接串和你的 [OpenAI API key](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)。 - -运行以下代码配置环境变量。你将被提示输入连接串和 OpenAI API key: - -```python -# 使用 getpass 在终端安全地输入环境变量。 -import getpass -import os - -# 连接串格式: "mysql+pymysql://:@:4000/?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" -tidb_connection_string = getpass.getpass("TiDB Connection String:") -os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") -``` - -以 macOS 为例,集群连接串如下: - -```dotenv -TIDB_DATABASE_URL="mysql+pymysql://:@:/" -# 例如: TIDB_DATABASE_URL="mysql+pymysql://root@127.0.0.1:4000/test" -``` - -你需要根据你的 TiDB 集群实际情况修改连接参数的值。如果你在本地运行 TiDB,`` 默认为 `127.0.0.1`。初始 `` 为空,因此首次启动集群时可以省略该字段。 - -各参数说明如下: - -- ``:连接 TiDB 集群的用户名。 -- ``:连接 TiDB 集群的密码。 -- ``:TiDB 集群的主机地址。 -- ``:TiDB 集群的端口号。 -- ``:你要连接的数据库名称。 - -
- -
- -### 步骤 4. 加载示例文档 - -#### 步骤 4.1 下载示例文档 - -在你的项目目录下,新建 `data/how_to/` 目录,并从 [langchain-ai/langchain](https://github.com/langchain-ai/langchain) GitHub 仓库下载示例文档 [`state_of_the_union.txt`](https://github.com/langchain-ai/langchain/blob/master/docs/docs/how_to/state_of_the_union.txt)。 - -```shell -!mkdir -p 'data/how_to/' -!wget 'https://raw.githubusercontent.com/langchain-ai/langchain/master/docs/docs/how_to/state_of_the_union.txt' -O 'data/how_to/state_of_the_union.txt' -``` - -#### 步骤 4.2 加载并切分文档 - -从 `data/how_to/state_of_the_union.txt` 加载示例文档,并使用 `CharacterTextSplitter` 将其切分为大约 1,000 个字符的块。 - -```python -loader = TextLoader("data/how_to/state_of_the_union.txt") -documents = loader.load() -text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) -docs = text_splitter.split_documents(documents) -``` - -### 步骤 5. 嵌入并存储文档向量 - -TiDB 向量存储支持余弦距离(`consine`)和欧氏距离(`l2`)两种向量相似度度量方式,默认策略为余弦距离。 - -以下代码将在 TiDB 中创建一个名为 `embedded_documents` 的表,该表已针对向量检索进行了优化。 - -```python -embeddings = OpenAIEmbeddings() -vector_store = TiDBVectorStore.from_documents( - documents=docs, - embedding=embeddings, - table_name="embedded_documents", - connection_string=tidb_connection_string, - distance_strategy="cosine", # default, another option is "l2" -) -``` - -执行成功后,你可以在 TiDB 数据库中直接查看和访问 `embedded_documents` 表。 - -### 步骤 6. 执行向量检索 - -本步骤演示如何在文档 `state_of_the_union.txt` 中查询 “What did the president say about Ketanji Brown Jackson”。 - -```python -query = "What did the president say about Ketanji Brown Jackson" -``` - -#### 选项 1:使用 `similarity_search_with_score()` - -`similarity_search_with_score()` 方法会计算文档与查询之间的向量空间距离。该距离作为相似度分数,由所选的 `distance_strategy` 决定。该方法返回分数最低的前 `k` 个文档。分数越低,文档与查询的相似度越高。 - -```python -docs_with_score = vector_store.similarity_search_with_score(query, k=3) -for doc, score in docs_with_score: - print("-" * 80) - print("Score: ", score) - print(doc.page_content) - print("-" * 80) -``` - -
- 期望输出 - -```plain --------------------------------------------------------------------------------- -Score: 0.18472413652518527 -Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. - -Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. - -One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. - -And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- -Score: 0.21757513022785557 -A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. - -And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. - -We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. - -We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. - -We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. - -We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- -Score: 0.22676987253721725 -And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. - -As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. - -While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. - -And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. - -So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. - -First, beat the opioid epidemic. --------------------------------------------------------------------------------- -``` - -
- -#### 选项 2:使用 `similarity_search_with_relevance_scores()` - -`similarity_search_with_relevance_scores()` 方法返回相关性分数最高的前 `k` 个文档。分数越高,文档与查询的相似度越高。 - -```python -docs_with_relevance_score = vector_store.similarity_search_with_relevance_scores(query, k=2) -for doc, score in docs_with_relevance_score: - print("-" * 80) - print("Score: ", score) - print(doc.page_content) - print("-" * 80) -``` - -
- 期望输出 - -```plain --------------------------------------------------------------------------------- -Score: 0.8152758634748147 -Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. - -Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. - -One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. - -And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- -Score: 0.7824248697721444 -A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. - -And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. - -We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. - -We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. - -We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. - -We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. --------------------------------------------------------------------------------- -``` - -
- -### 作为检索器使用 - -在 Langchain 中,[retriever](https://python.langchain.com/v0.2/docs/concepts/#retrievers) 是一个用于响应非结构化查询检索文档的接口,功能比向量存储更丰富。以下代码演示如何将 TiDB 向量存储作为检索器使用。 - -```python -retriever = vector_store.as_retriever( - search_type="similarity_score_threshold", - search_kwargs={"k": 3, "score_threshold": 0.8}, -) -docs_retrieved = retriever.invoke(query) -for doc in docs_retrieved: - print("-" * 80) - print(doc.page_content) - print("-" * 80) -``` - -期望输出如下: - -``` --------------------------------------------------------------------------------- -Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. - -Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. - -One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. - -And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. --------------------------------------------------------------------------------- -``` - -### 移除向量存储 - -要移除已存在的 TiDB 向量存储,可使用 `drop_vectorstore()` 方法: - -```python -vector_store.drop_vectorstore() -``` - -## 使用元数据过滤进行检索 - -为了进一步优化检索结果,你可以使用元数据过滤器,仅返回符合过滤条件的最近邻结果。 - -### 支持的元数据类型 - -TiDB 向量存储中的每个文档都可以配有元数据,元数据以 JSON 对象的键值对形式存储。键始终为字符串,值可以是以下类型之一: - -- 字符串 -- 数值:整数或浮点数 -- 布尔值:`true` 或 `false` - -例如,以下是一个合法的元数据负载: - -```json -{ - "page": 12, - "book_title": "Siddhartha" -} -``` - -### 元数据过滤语法 - -可用的过滤器包括: - -- `$or`:匹配任意一个条件的向量。 -- `$and`:同时匹配所有条件的向量。 -- `$eq`:等于指定值。 -- `$ne`:不等于指定值。 -- `$gt`:大于指定值。 -- `$gte`:大于等于指定值。 -- `$lt`:小于指定值。 -- `$lte`:小于等于指定值。 -- `$in`:在指定值数组中。 -- `$nin`:不在指定值数组中。 - -如果某个文档的元数据如下: - -```json -{ - "page": 12, - "book_title": "Siddhartha" -} -``` - -以下元数据过滤器都可以匹配该文档: - -```json -{ "page": 12 } -``` - -```json -{ "page": { "$eq": 12 } } -``` - -```json -{ - "page": { - "$in": [11, 12, 13] - } -} -``` - -```json -{ "page": { "$nin": [13] } } -``` - -```json -{ "page": { "$lt": 11 } } -``` - -```json -{ - "$or": [{ "page": 11 }, { "page": 12 }], - "$and": [{ "page": 12 }, { "page": 13 }] -} -``` - -在元数据过滤器中,TiDB 会将每个键值对视为一个独立的过滤条件,并使用 `AND` 逻辑操作符将这些条件组合。 - -### 示例 - -以下示例向 `TiDBVectorStore` 添加两个文档,并为每个文档添加 `title` 字段作为元数据: - -```python -vector_store.add_texts( - texts=[ - "TiDB Vector offers advanced, high-speed vector processing capabilities, enhancing AI workflows with efficient data handling and analytics support.", - "TiDB Vector, starting as low as $10 per month for basic usage", - ], - metadatas=[ - {"title": "TiDB Vector functionality"}, - {"title": "TiDB Vector Pricing"}, - ], -) -``` - -期望输出如下: - -```plain -[UUID('c782cb02-8eec-45be-a31f-fdb78914f0a7'), - UUID('08dcd2ba-9f16-4f29-a9b7-18141f8edae3')] -``` - -使用元数据过滤器进行相似度检索: - -```python -docs_with_score = vector_store.similarity_search_with_score( - "Introduction to TiDB Vector", filter={"title": "TiDB Vector functionality"}, k=4 -) -for doc, score in docs_with_score: - print("-" * 80) - print("Score: ", score) - print(doc.page_content) - print("-" * 80) -``` - -期望输出如下: - -```plain --------------------------------------------------------------------------------- -Score: 0.12761409169211535 -TiDB Vector offers advanced, high-speed vector processing capabilities, enhancing AI workflows with efficient data handling and analytics support. --------------------------------------------------------------------------------- -``` - -## 高级用法示例:旅行社场景 - -本节演示将向量检索与 Langchain 集成的旅行社场景。目标是为客户生成个性化旅行报告,帮助他们找到拥有特定设施(如干净的休息室和素食选项)的机场。 - -流程主要分为两步: - -1. 对机场评论进行语义检索,找出符合所需设施的机场代码。 -2. 执行 SQL 查询,将这些代码与航线信息关联,突出显示符合用户偏好的航空公司和目的地。 - -### 准备数据 - -首先,创建一个用于存储机场航线数据的表: - -```python -# 创建用于存储航班计划数据的表。 -vector_store.tidb_vector_client.execute( - """CREATE TABLE airplan_routes ( - id INT AUTO_INCREMENT PRIMARY KEY, - airport_code VARCHAR(10), - airline_code VARCHAR(10), - destination_code VARCHAR(10), - route_details TEXT, - duration TIME, - frequency INT, - airplane_type VARCHAR(50), - price DECIMAL(10, 2), - layover TEXT - );""" -) - -# 向 airplan_routes 和向量表中插入一些示例数据。 -vector_store.tidb_vector_client.execute( - """INSERT INTO airplan_routes ( - airport_code, - airline_code, - destination_code, - route_details, - duration, - frequency, - airplane_type, - price, - layover - ) VALUES - ('JFK', 'DL', 'LAX', 'Non-stop from JFK to LAX.', '06:00:00', 5, 'Boeing 777', 299.99, 'None'), - ('LAX', 'AA', 'ORD', 'Direct LAX to ORD route.', '04:00:00', 3, 'Airbus A320', 149.99, 'None'), - ('EFGH', 'UA', 'SEA', 'Daily flights from SFO to SEA.', '02:30:00', 7, 'Boeing 737', 129.99, 'None'); - """ -) -vector_store.add_texts( - texts=[ - "Clean lounges and excellent vegetarian dining options. Highly recommended.", - "Comfortable seating in lounge areas and diverse food selections, including vegetarian.", - "Small airport with basic facilities.", - ], - metadatas=[ - {"airport_code": "JFK"}, - {"airport_code": "LAX"}, - {"airport_code": "EFGH"}, - ], -) -``` - -期望输出如下: - -```plain -[UUID('6dab390f-acd9-4c7d-b252-616606fbc89b'), - UUID('9e811801-0e6b-4893-8886-60f4fb67ce69'), - UUID('f426747c-0f7b-4c62-97ed-3eeb7c8dd76e')] -``` - -### 执行语义检索 - -以下代码检索拥有干净设施和素食选项的机场: - -```python -retriever = vector_store.as_retriever( - search_type="similarity_score_threshold", - search_kwargs={"k": 3, "score_threshold": 0.85}, -) -semantic_query = "Could you recommend a US airport with clean lounges and good vegetarian dining options?" -reviews = retriever.invoke(semantic_query) -for r in reviews: - print("-" * 80) - print(r.page_content) - print(r.metadata) - print("-" * 80) -``` - -期望输出如下: - -```plain --------------------------------------------------------------------------------- -Clean lounges and excellent vegetarian dining options. Highly recommended. -{'airport_code': 'JFK'} --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- -Comfortable seating in lounge areas and diverse food selections, including vegetarian. -{'airport_code': 'LAX'} --------------------------------------------------------------------------------- -``` - -### 获取机场详细信息 - -从检索结果中提取机场代码,并查询数据库获取详细航线信息: - -```python -# 从元数据中提取机场代码 -airport_codes = [review.metadata["airport_code"] for review in reviews] - -# 执行查询获取机场详细信息 -search_query = "SELECT * FROM airplan_routes WHERE airport_code IN :codes" -params = {"codes": tuple(airport_codes)} - -airport_details = vector_store.tidb_vector_client.execute(search_query, params) -airport_details.get("result") -``` - -期望输出如下: - -```plain -[(1, 'JFK', 'DL', 'LAX', 'Non-stop from JFK to LAX.', datetime.timedelta(seconds=21600), 5, 'Boeing 777', Decimal('299.99'), 'None'), - (2, 'LAX', 'AA', 'ORD', 'Direct LAX to ORD route.', datetime.timedelta(seconds=14400), 3, 'Airbus A320', Decimal('149.99'), 'None')] -``` - -### 流程简化 - -你也可以通过一条 SQL 查询简化整个流程: - -```python -search_query = f""" - SELECT - VEC_Cosine_Distance(se.embedding, :query_vector) as distance, - ar.*, - se.document as airport_review - FROM - airplan_routes ar - JOIN - {TABLE_NAME} se ON ar.airport_code = JSON_UNQUOTE(JSON_EXTRACT(se.meta, '$.airport_code')) - ORDER BY distance ASC - LIMIT 5; -""" -query_vector = embeddings.embed_query(semantic_query) -params = {"query_vector": str(query_vector)} -airport_details = vector_store.tidb_vector_client.execute(search_query, params) -airport_details.get("result") -``` - -期望输出如下: - -```plain -[(0.1219207353407008, 1, 'JFK', 'DL', 'LAX', 'Non-stop from JFK to LAX.', datetime.timedelta(seconds=21600), 5, 'Boeing 777', Decimal('299.99'), 'None', 'Clean lounges and excellent vegetarian dining options. Highly recommended.'), - (0.14613754359804654, 2, 'LAX', 'AA', 'ORD', 'Direct LAX to ORD route.', datetime.timedelta(seconds=14400), 3, 'Airbus A320', Decimal('149.99'), 'None', 'Comfortable seating in lounge areas and diverse food selections, including vegetarian.'), - (0.19840519342700513, 3, 'EFGH', 'UA', 'SEA', 'Daily flights from SFO to SEA.', datetime.timedelta(seconds=9000), 7, 'Boeing 737', Decimal('129.99'), 'None', 'Small airport with basic facilities.')] -``` - -### 清理数据 - -最后,通过删除创建的表来清理资源: - -```python -vector_store.tidb_vector_client.execute("DROP TABLE airplan_routes") -``` - -期望输出如下: - -```plain -{'success': True, 'result': 0, 'error': None} -``` - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-integrate-with-llamaindex.md b/vector-search/vector-search-integrate-with-llamaindex.md deleted file mode 100644 index 3aedc46845085..0000000000000 --- a/vector-search/vector-search-integrate-with-llamaindex.md +++ /dev/null @@ -1,342 +0,0 @@ ---- -title: 集成 Vector Search 与 LlamaIndex -summary: 了解如何将 TiDB Vector Search 集成到 LlamaIndex 中。 ---- - -# 集成 Vector Search 与 LlamaIndex - -本教程演示如何将 TiDB 的 [vector search](/vector-search/vector-search-overview.md) 功能与 [LlamaIndex](https://www.llamaindex.ai) 集成。 - - - -> **Warning:** -> -> 向量检索功能目前为实验性功能。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能目前为 beta 版本。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 及以上(推荐 v8.5.0 及以上)。 - -> **Tip** -> -> 你可以在 Jupyter Notebook 查看完整的 [示例代码](https://github.com/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/TiDBVector.ipynb),或直接在 [Colab](https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/TiDBVector.ipynb) 在线环境中运行示例代码。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Jupyter Notebook](https://jupyter.org/install)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 快速开始 - -本节将提供将 TiDB Vector Search 与 LlamaIndex 集成以进行语义检索的分步指南。 - -### 步骤 1. 新建 Jupyter Notebook 文件 - -在项目根目录下,新建一个名为 `integrate_with_llamaindex.ipynb` 的 Jupyter Notebook 文件: - -```shell -touch integrate_with_llamaindex.ipynb -``` - -### 步骤 2. 安装所需依赖 - -在你的项目目录下,运行以下命令安装所需的依赖包: - -```shell -pip install llama-index-vector-stores-tidbvector -pip install llama-index -``` - -在 Jupyter Notebook 中打开 `integrate_with_llamaindex.ipynb` 文件,并添加以下代码以导入所需包: - -```python -import textwrap - -from llama_index.core import SimpleDirectoryReader, StorageContext -from llama_index.core import VectorStoreIndex -from llama_index.vector_stores.tidbvector import TiDBVectorStore -``` - -### 步骤 3. 配置环境变量 - -根据你选择的 TiDB 部署方式配置环境变量。 - - -
- -对于 TiDB Cloud Starter 集群,按以下步骤获取集群连接串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确认连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public`。 - - **Branch** 设置为 `main`。 - - **Connect With** 设置为 `SQLAlchemy`。 - - **Operating System** 与你的环境一致。 - -4. 点击 **PyMySQL** 标签页,复制连接串。 - - > **Tip:** - > - > 如果你还未设置密码,可点击 **Generate Password** 生成随机密码。 - -5. 配置环境变量。 - - 本文档以 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型提供方为例。在此步骤中,你需要提供上一步获取的连接串和你的 [OpenAI API key](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)。 - - 运行以下代码配置环境变量。你将被提示输入连接串和 OpenAI API key: - - ```python - # 使用 getpass 在终端安全地输入环境变量。 - import getpass - import os - - # 从 TiDB Cloud 控制台复制你的连接串。 - # 连接串格式: "mysql+pymysql://:@:4000/?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" - tidb_connection_string = getpass.getpass("TiDB Connection String:") - os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") - ``` - -
-
- -本文档以 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型提供方为例。在此步骤中,你需要提供 TiDB 集群的连接串和你的 [OpenAI API key](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)。 - -运行以下代码配置环境变量。你将被提示输入连接串和 OpenAI API key: - -```python -# 使用 getpass 在终端安全地输入环境变量。 -import getpass -import os - -# 连接串格式: "mysql+pymysql://:@:4000/?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" -tidb_connection_string = getpass.getpass("TiDB Connection String:") -os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") -``` - -以 macOS 为例,集群连接串如下: - -```dotenv -TIDB_DATABASE_URL="mysql+pymysql://:@:/" -# 例如: TIDB_DATABASE_URL="mysql+pymysql://root@127.0.0.1:4000/test" -``` - -你需要根据自己的 TiDB 集群修改连接串中的参数。如果你在本地运行 TiDB,`` 默认为 `127.0.0.1`。初始 `` 为空,因此首次启动集群时可以省略该字段。 - -各参数说明如下: - -- ``:连接 TiDB 集群的用户名。 -- ``:连接 TiDB 集群的密码。 -- ``:TiDB 集群的主机地址。 -- ``:TiDB 集群的端口号。 -- ``:你要连接的数据库名称。 - -
- -
- -### 步骤 4. 加载示例文档 - -#### 步骤 4.1 下载示例文档 - -在你的项目目录下,新建目录 `data/paul_graham/`,并从 [run-llama/llama_index](https://github.com/run-llama/llama_index) GitHub 仓库下载示例文档 [`paul_graham_essay.txt`](https://github.com/run-llama/llama_index/blob/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt)。 - -```shell -!mkdir -p 'data/paul_graham/' -!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt' -``` - -#### 步骤 4.2 加载文档 - -使用 `SimpleDirectoryReader` 类从 `data/paul_graham/paul_graham_essay.txt` 加载示例文档。 - -```python -documents = SimpleDirectoryReader("./data/paul_graham").load_data() -print("Document ID:", documents[0].doc_id) - -for index, document in enumerate(documents): - document.metadata = {"book": "paul_graham"} -``` - -### 步骤 5. 嵌入并存储文档向量 - -#### 步骤 5.1 初始化 TiDB 向量存储 - -以下代码会在 TiDB 中创建一个名为 `paul_graham_test` 的表,该表已针对向量检索进行了优化。 - -```python -tidbvec = TiDBVectorStore( - connection_string=tidb_connection_url, - table_name="paul_graham_test", - distance_strategy="cosine", - vector_dimension=1536, - drop_existing_table=False, -) -``` - -执行成功后,你可以在 TiDB 数据库中直接查看和访问 `paul_graham_test` 表。 - -#### 步骤 5.2 生成并存储嵌入向量 - -以下代码会解析文档,生成嵌入向量,并将其存储到 TiDB 向量存储中。 - -```python -storage_context = StorageContext.from_defaults(vector_store=tidbvec) -index = VectorStoreIndex.from_documents( - documents, storage_context=storage_context, show_progress=True -) -``` - -预期输出如下: - -```plain -Parsing nodes: 100%|██████████| 1/1 [00:00<00:00, 8.76it/s] -Generating embeddings: 100%|██████████| 21/21 [00:02<00:00, 8.22it/s] -``` - -### 步骤 6. 执行向量检索 - -以下代码基于 TiDB 向量存储创建查询引擎,并执行语义相似度检索。 - -```python -query_engine = index.as_query_engine() -response = query_engine.query("What did the author do?") -print(textwrap.fill(str(response), 100)) -``` - -> **Note** -> -> `TiDBVectorStore` 仅支持 [`default`](https://docs.llamaindex.ai/en/stable/api_reference/storage/vector_store/?h=vectorstorequerymode#llama_index.core.vector_stores.types.VectorStoreQueryMode) 查询模式。 - -预期输出如下: - -```plain -The author worked on writing, programming, building microcomputers, giving talks at conferences, -publishing essays online, developing spam filters, painting, hosting dinner parties, and purchasing -a building for office use. -``` - -### 步骤 7. 使用元数据过滤器进行检索 - -为了优化检索结果,你可以使用元数据过滤器,仅返回符合过滤条件的最近邻结果。 - -#### 使用 `book != "paul_graham"` 过滤器查询 - -以下示例会排除 `book` 元数据字段为 `"paul_graham"` 的结果: - -```python -from llama_index.core.vector_stores.types import ( - MetadataFilter, - MetadataFilters, -) - -query_engine = index.as_query_engine( - filters=MetadataFilters( - filters=[ - MetadataFilter(key="book", value="paul_graham", operator="!="), - ] - ), - similarity_top_k=2, -) -response = query_engine.query("What did the author learn?") -print(textwrap.fill(str(response), 100)) -``` - -预期输出如下: - -```plain -Empty Response -``` - -#### 使用 `book == "paul_graham"` 过滤器查询 - -以下示例仅返回 `book` 元数据字段为 `"paul_graham"` 的文档: - -```python -from llama_index.core.vector_stores.types import ( - MetadataFilter, - MetadataFilters, -) - -query_engine = index.as_query_engine( - filters=MetadataFilters( - filters=[ - MetadataFilter(key="book", value="paul_graham", operator="=="), - ] - ), - similarity_top_k=2, -) -response = query_engine.query("What did the author learn?") -print(textwrap.fill(str(response), 100)) -``` - -预期输出如下: - -```plain -The author learned programming on an IBM 1401 using an early version of Fortran in 9th grade, then -later transitioned to working with microcomputers like the TRS-80 and Apple II. Additionally, the -author studied philosophy in college but found it unfulfilling, leading to a switch to studying AI. -Later on, the author attended art school in both the US and Italy, where they observed a lack of -substantial teaching in the painting department. -``` - -### 步骤 8. 删除文档 - -从索引中删除第一个文档: - -```python -tidbvec.delete(documents[0].doc_id) -``` - -检查文档是否已被删除: - -```python -query_engine = index.as_query_engine() -response = query_engine.query("What did the author learn?") -print(textwrap.fill(str(response), 100)) -``` - -预期输出如下: - -```plain -Empty Response -``` - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-integrate-with-peewee.md b/vector-search/vector-search-integrate-with-peewee.md deleted file mode 100644 index d4cf71196a780..0000000000000 --- a/vector-search/vector-search-integrate-with-peewee.md +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: 将 TiDB 向量检索集成到 peewee -summary: 学习如何将 TiDB 向量检索与 peewee 集成,以存储嵌入向量并执行语义检索。 ---- - -# 将 TiDB 向量检索集成到 peewee - -本教程将指导你如何使用 [peewee](https://docs.peewee-orm.com/) 与 [TiDB 向量检索](/vector-search/vector-search-overview.md) 进行交互,存储嵌入向量,并执行向量检索查询。 - - - -> **Warning:** -> -> 向量检索功能为实验性功能。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能处于 beta 阶段,可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 运行示例应用 - -你可以按照以下步骤快速了解如何将 TiDB 向量检索与 peewee 集成。 - -### 步骤 1. 克隆代码仓库 - -将 [`tidb-vector-python`](https://github.com/pingcap/tidb-vector-python) 仓库克隆到本地: - -```shell -git clone https://github.com/pingcap/tidb-vector-python.git -``` - -### 步骤 2. 创建虚拟环境 - -为你的项目创建一个虚拟环境: - -```bash -cd tidb-vector-python/examples/orm-peewee-quickstart -python3 -m venv .venv -source .venv/bin/activate -``` - -### 步骤 3. 安装所需依赖 - -为示例项目安装所需依赖: - -```bash -pip install -r requirements.txt -``` - -或者,你也可以为你的项目单独安装以下包: - -```bash -pip install peewee pymysql python-dotenv tidb-vector -``` - -### 步骤 4. 配置环境变量 - -根据你选择的 TiDB 部署方式配置环境变量。 - - -
- -对于 TiDB Cloud Starter 集群,按以下步骤获取集群连接字符串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确保连接对话框中的配置与你的操作环境一致。 - - - **Connection Type** 设置为 `Public`。 - - **Branch** 设置为 `main`。 - - **Connect With** 设置为 `General`。 - - **Operating System** 与你的环境一致。 - - > **Tip:** - > - > 如果你的程序运行在 Windows Subsystem for Linux (WSL) 中,请切换到对应的 Linux 发行版。 - -4. 从连接对话框中复制连接参数。 - - > **Tip:** - > - > 如果你还没有设置密码,可以点击 **Generate Password** 生成一个随机密码。 - -5. 在你的 Python 项目根目录下创建 `.env` 文件,并将连接参数粘贴到对应的环境变量中。 - - - `TIDB_HOST`:TiDB 集群的主机地址。 - - `TIDB_PORT`:TiDB 集群的端口。 - - `TIDB_USERNAME`:连接 TiDB 集群的用户名。 - - `TIDB_PASSWORD`:连接 TiDB 集群的密码。 - - `TIDB_DATABASE`:要连接的数据库名。 - - `TIDB_CA_PATH`:根证书文件的路径。 - - 以下是 macOS 的示例: - - ```dotenv - TIDB_HOST=gateway01.****.prod.aws.tidbcloud.com - TIDB_PORT=4000 - TIDB_USERNAME=********.root - TIDB_PASSWORD=******** - TIDB_DATABASE=test - TIDB_CA_PATH=/etc/ssl/cert.pem - ``` - -
-
- -对于 TiDB 自建集群,在你的 Python 项目根目录下创建 `.env` 文件。将以下内容复制到 `.env` 文件中,并根据你的 TiDB 集群连接参数修改环境变量的值: - -```dotenv -TIDB_HOST=127.0.0.1 -TIDB_PORT=4000 -TIDB_USERNAME=root -TIDB_PASSWORD= -TIDB_DATABASE=test -``` - -如果你在本地运行 TiDB,`TIDB_HOST` 默认为 `127.0.0.1`。初始的 `TIDB_PASSWORD` 为空,因此如果你是首次启动集群,可以省略该字段。 - -各参数说明如下: - -- `TIDB_HOST`:TiDB 集群的主机地址。 -- `TIDB_PORT`:TiDB 集群的端口。 -- `TIDB_USERNAME`:连接 TiDB 集群的用户名。 -- `TIDB_PASSWORD`:连接 TiDB 集群的密码。 -- `TIDB_DATABASE`:你要连接的数据库名称。 - -
- -
- -### 步骤 5. 运行示例 - -```bash -python peewee-quickstart.py -``` - -示例输出: - -```text -Get 3-nearest neighbor documents: - - distance: 0.00853986601633272 - document: fish - - distance: 0.12712843905603044 - document: dog - - distance: 0.7327387580875756 - document: tree -Get documents within a certain distance: - - distance: 0.00853986601633272 - document: fish - - distance: 0.12712843905603044 - document: dog -``` - -## 示例代码片段 - -你可以参考以下示例代码片段开发你的应用。 - -### 创建向量表 - -#### 连接 TiDB 集群 - -```python -import os -import dotenv - -from peewee import Model, MySQLDatabase, SQL, TextField -from tidb_vector.peewee import VectorField - -dotenv.load_dotenv() - -# Using `pymysql` as the driver. -connect_kwargs = { - 'ssl_verify_cert': True, - 'ssl_verify_identity': True, -} - -# Using `mysqlclient` as the driver. -# connect_kwargs = { -# 'ssl_mode': 'VERIFY_IDENTITY', -# 'ssl': { -# # Root certificate default path -# # https://docs.pingcap.com/tidbcloud/secure-connections-to-serverless-clusters/#root-certificate-default-path -# 'ca': os.environ.get('TIDB_CA_PATH', '/path/to/ca.pem'), -# }, -# } - -db = MySQLDatabase( - database=os.environ.get('TIDB_DATABASE', 'test'), - user=os.environ.get('TIDB_USERNAME', 'root'), - password=os.environ.get('TIDB_PASSWORD', ''), - host=os.environ.get('TIDB_HOST', 'localhost'), - port=int(os.environ.get('TIDB_PORT', '4000')), - **connect_kwargs, -) -``` - -#### 定义向量列 - -创建一个包含名为 `peewee_demo_documents` 的表,并存储 3 维向量。 - -```python -class Document(Model): - class Meta: - database = db - table_name = 'peewee_demo_documents' - - content = TextField() - embedding = VectorField(3) -``` - -### 存储带嵌入向量的文档 - -```python -Document.create(content='dog', embedding=[1, 2, 1]) -Document.create(content='fish', embedding=[1, 2, 4]) -Document.create(content='tree', embedding=[1, 0, 0]) -``` - -### 检索最近邻文档 - -基于余弦距离函数,检索与查询向量 `[1, 2, 3]` 语义最接近的前 3 个文档。 - -```python -distance = Document.embedding.cosine_distance([1, 2, 3]).alias('distance') -results = Document.select(Document, distance).order_by(distance).limit(3) -``` - -### 检索距离在指定范围内的文档 - -检索与查询向量 `[1, 2, 3]` 的余弦距离小于 0.2 的文档。 - -```python -distance_expression = Document.embedding.cosine_distance([1, 2, 3]) -distance = distance_expression.alias('distance') -results = Document.select(Document, distance).where(distance_expression < 0.2).order_by(distance).limit(3) -``` - -## 相关阅读 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-integrate-with-sqlalchemy.md b/vector-search/vector-search-integrate-with-sqlalchemy.md deleted file mode 100644 index 284e4bd70c77e..0000000000000 --- a/vector-search/vector-search-integrate-with-sqlalchemy.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: 将 TiDB 向量检索集成到 SQLAlchemy -summary: 学习如何将 TiDB 向量检索与 SQLAlchemy 集成,用于存储嵌入向量并执行语义检索。 ---- - -# 将 TiDB 向量检索集成到 SQLAlchemy - -本教程将指导你如何使用 [SQLAlchemy](https://www.sqlalchemy.org/) 与 [TiDB 向量检索](/vector-search/vector-search-overview.md) 进行交互,存储嵌入向量,并执行向量检索查询。 - - - -> **Warning:** -> -> 向量检索功能目前为实验性功能。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能目前为 Beta 版本。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 前置条件 - -完成本教程,你需要: - -- 已安装 [Python 3.8 或更高版本](https://www.python.org/downloads/)。 -- 已安装 [Git](https://git-scm.com/downloads)。 -- 一个 TiDB 集群。 - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- 参考 [部署本地测试 TiDB 集群](/quick-start-with-tidb.md#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](/production-deployment-using-tiup.md) 创建本地集群。 -- 参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 - - - - -**如果你还没有 TiDB 集群,可以按如下方式创建:** - -- (推荐)参考 [创建 TiDB Cloud Starter 集群](/develop/dev-guide-build-cluster-in-cloud.md) 创建属于你自己的 TiDB Cloud 集群。 -- 参考 [部署本地测试 TiDB 集群](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) 或 [部署生产环境 TiDB 集群](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) 创建 v8.4.0 或更高版本的本地集群。 - - - -## 运行示例应用 - -你可以按照以下步骤快速了解如何将 TiDB 向量检索与 SQLAlchemy 集成。 - -### 步骤 1. 克隆代码仓库 - -将 `tidb-vector-python` 仓库克隆到本地: - -```shell -git clone https://github.com/pingcap/tidb-vector-python.git -``` - -### 步骤 2. 创建虚拟环境 - -为你的项目创建一个虚拟环境: - -```bash -cd tidb-vector-python/examples/orm-sqlalchemy-quickstart -python3 -m venv .venv -source .venv/bin/activate -``` - -### 步骤 3. 安装所需依赖 - -为示例项目安装所需依赖: - -```bash -pip install -r requirements.txt -``` - -或者,你也可以为你的项目单独安装以下包: - -```bash -pip install pymysql python-dotenv sqlalchemy tidb-vector -``` - -### 步骤 4. 配置环境变量 - -根据你选择的 TiDB 部署方式配置环境变量。 - - -
- -对于 TiDB Cloud Starter 集群,按以下步骤获取集群连接字符串并配置环境变量: - -1. 进入 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,然后点击目标集群名称进入集群概览页。 - -2. 点击右上角的 **Connect**,弹出连接对话框。 - -3. 确保连接对话框中的配置与你的环境一致。 - - - **Connection Type** 设置为 `Public`。 - - **Branch** 设置为 `main`。 - - **Connect With** 设置为 `SQLAlchemy`。 - - **Operating System** 与你的环境一致。 - - > **Tip:** - > - > 如果你的程序运行在 Windows Subsystem for Linux (WSL) 中,请切换到对应的 Linux 发行版。 - -4. 点击 **PyMySQL** 标签页并复制连接字符串。 - - > **Tip:** - > - > 如果你还没有设置密码,可以点击 **Generate Password** 生成一个随机密码。 - -5. 在你的 Python 项目根目录下创建 `.env` 文件,并将连接字符串粘贴进去。 - - 以下是 macOS 的示例: - - ```dotenv - TIDB_DATABASE_URL="mysql+pymysql://.root:@gateway01..prod.aws.tidbcloud.com:4000/test?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true" - ``` - -
-
- -对于 TiDB 自建集群,在你的 Python 项目根目录下创建 `.env` 文件。将以下内容复制到 `.env` 文件中,并根据你的 TiDB 集群连接参数修改环境变量的值: - -```dotenv -TIDB_DATABASE_URL="mysql+pymysql://:@:/" -# 例如:TIDB_DATABASE_URL="mysql+pymysql://root@127.0.0.1:4000/test" -``` - -如果你在本地运行 TiDB,`` 默认为 `127.0.0.1`。初始 `` 为空,因此如果你是首次启动集群,可以省略该字段。 - -各参数说明如下: - -- ``:连接 TiDB 集群的用户名。 -- ``:连接 TiDB 集群的密码。 -- ``:TiDB 集群的主机地址。 -- ``:TiDB 集群的端口号。 -- ``:你要连接的数据库名称。 - -
- -
- -### 步骤 5. 运行示例 - -```bash -python sqlalchemy-quickstart.py -``` - -示例输出: - -```text -Get 3-nearest neighbor documents: - - distance: 0.00853986601633272 - document: fish - - distance: 0.12712843905603044 - document: dog - - distance: 0.7327387580875756 - document: tree -Get documents within a certain distance: - - distance: 0.00853986601633272 - document: fish - - distance: 0.12712843905603044 - document: dog -``` - -## 示例代码片段 - -你可以参考以下示例代码片段开发你的应用。 - -### 创建向量表 - -#### 连接 TiDB 集群 - -```python -import os -import dotenv - -from sqlalchemy import Column, Integer, create_engine, Text -from sqlalchemy.orm import declarative_base, Session -from tidb_vector.sqlalchemy import VectorType - -dotenv.load_dotenv() - -tidb_connection_string = os.environ['TIDB_DATABASE_URL'] -engine = create_engine(tidb_connection_string) -``` - -#### 定义向量列 - -创建一个包含名为 `embedding` 的 3 维向量列的表。 - -```python -Base = declarative_base() - -class Document(Base): - __tablename__ = 'sqlalchemy_demo_documents' - id = Column(Integer, primary_key=True) - content = Column(Text) - embedding = Column(VectorType(3)) -``` - -### 存储带嵌入向量的文档 - -```python -with Session(engine) as session: - session.add(Document(content="dog", embedding=[1, 2, 1])) - session.add(Document(content="fish", embedding=[1, 2, 4])) - session.add(Document(content="tree", embedding=[1, 0, 0])) - session.commit() -``` - -### 检索最近邻文档 - -基于余弦距离函数,检索与查询向量 `[1, 2, 3]` 语义最接近的前 3 个文档。 - -```python -with Session(engine) as session: - distance = Document.embedding.cosine_distance([1, 2, 3]).label('distance') - results = session.query( - Document, distance - ).order_by(distance).limit(3).all() -``` - -### 检索距离在指定范围内的文档 - -检索与查询向量 `[1, 2, 3]` 的余弦距离小于 0.2 的文档。 - -```python -with Session(engine) as session: - distance = Document.embedding.cosine_distance([1, 2, 3]).label('distance') - results = session.query( - Document, distance - ).filter(distance < 0.2).order_by(distance).limit(3).all() -``` - -## 参见 - -- [向量数据类型](/vector-search/vector-search-data-types.md) -- [向量检索索引](/vector-search/vector-search-index.md) diff --git a/vector-search/vector-search-overview.md b/vector-search/vector-search-overview.md deleted file mode 100644 index e419f8ea8de67..0000000000000 --- a/vector-search/vector-search-overview.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Vector Search Overview -summary: 了解 TiDB 中的向量检索功能。该功能为文档、图片、音频和视频等多种数据类型提供了先进的语义相似性检索解决方案。 ---- - -# 向量检索概述 - -向量检索为文档、图片、音频和视频等多种数据类型的语义相似性检索提供了强大的解决方案。它允许开发者利用自己的 MySQL 专业知识,构建具备生成式 AI 能力的可扩展应用,简化高级检索功能的集成。 - - - -> **Warning:** -> -> 向量检索功能目前为实验性功能。不建议在生产环境中使用。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - - - -> **Note:** -> -> 向量检索功能目前为 beta 版本。该功能可能会在没有提前通知的情况下发生变更。如果你发现了 bug,可以在 GitHub 上提交 [issue](https://github.com/pingcap/tidb/issues)。 - - - -> **Note:** -> -> 向量检索功能适用于 TiDB 自建版、[TiDB Cloud Starter](https://docs.pingcap.com/tidbcloud/select-cluster-tier#starter)、[TiDB Cloud Essential](https://docs.pingcap.com/tidbcloud/select-cluster-tier#essential) 和 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier#tidb-cloud-dedicated)。对于 TiDB 自建版和 TiDB Cloud Dedicated,TiDB 版本需为 v8.4.0 或更高(推荐 v8.5.0 或更高)。 - -## 概念 - -向量检索是一种以数据语义为核心、提供相关性结果的检索方法。 - -与传统的全文检索依赖于精确的关键词匹配和词频不同,向量检索会将多种数据类型(如文本、图片或音频)转换为高维向量,并基于这些向量之间的相似度进行查询。这种检索方式能够捕捉数据的语义含义和上下文信息,从而更准确地理解用户意图。 - -即使检索词与数据库中的内容并不完全匹配,向量检索也可以通过分析数据的语义,返回符合用户意图的结果。 - -例如,全文检索 “a swimming animal” 只会返回包含这些精确关键词的结果。而向量检索则可以返回其他游泳动物(如鱼或鸭子)的结果,即使这些结果中并不包含完全相同的关键词。 - -### 向量嵌入 - -向量嵌入(vector embedding),也称为 embedding,是一组数字序列,用于在高维空间中表示现实世界的对象。它能够捕捉非结构化数据(如文档、图片、音频和视频)的语义和上下文信息。 - -向量嵌入在机器学习中至关重要,是语义相似性检索的基础。 - -TiDB 引入了专为优化向量嵌入存储和检索设计的 [Vector data types](/vector-search/vector-search-data-types.md) 和 [Vector search index](/vector-search/vector-search-index.md),提升了其在 AI 应用中的使用效率。你可以将向量嵌入存储在 TiDB 中,并通过这些数据类型执行向量检索查询,查找最相关的数据。 - -### 嵌入模型 - -嵌入模型(embedding model)是一种将数据转换为 [vector embeddings](#vector-embedding) 的算法。 - -选择合适的嵌入模型对于确保语义检索结果的准确性和相关性至关重要。对于非结构化文本数据,你可以在 [Massive Text Embedding Benchmark (MTEB) Leaderboard](https://huggingface.co/spaces/mteb/leaderboard) 上找到表现最优的文本嵌入模型。 - -如需了解如何为你的特定数据类型生成向量嵌入,请参考集成教程或嵌入模型的示例。 - -## 向量检索的工作原理 - -在将原始数据转换为向量嵌入并存储到 TiDB 后,你的应用可以执行向量检索查询,查找与用户查询在语义或上下文上最相关的数据。 - -TiDB 向量检索通过使用 [distance function](/vector-search/vector-search-functions-and-operators.md) 计算给定向量与数据库中已存向量之间的距离,从而识别出 top-k 最近邻(KNN)向量。与查询向量距离最近的向量,代表在语义上最相似的数据。 - -![The Schematic TiDB Vector Search](/media/vector-search/embedding-search.png) - -作为一款集成了向量检索能力的关系型数据库,TiDB 允许你将数据及其对应的向量表示(即向量嵌入)一同存储在同一个数据库中。你可以选择以下任意一种存储方式: - -- 在同一张表的不同列中存储数据及其对应的向量表示。 -- 在不同的表中分别存储数据及其对应的向量表示。此时,在检索数据时需要通过 `JOIN` 查询将表进行关联。 - -## 应用场景 - -### 检索增强生成(RAG) - -检索增强生成(Retrieval-Augmented Generation,RAG)是一种旨在优化大语言模型(LLM)输出的架构。通过向量检索,RAG 应用可以将向量嵌入存储在数据库中,并在 LLM 生成响应时检索相关文档作为额外上下文,从而提升答案的质量和相关性。 - -### 语义检索 - -语义检索是一种基于查询语义返回结果的检索技术,而不仅仅是简单的关键词匹配。它通过嵌入方式理解不同语言和多种数据类型(如文本、图片和音频)的含义。向量检索算法随后利用这些嵌入,查找最能满足用户查询需求的相关数据。 - -### 推荐引擎 - -推荐引擎是一种能够主动为用户推荐相关且个性化内容、产品或服务的系统。它通过创建能够代表用户行为和偏好的嵌入,帮助系统识别其他用户曾经互动或感兴趣的相似项目,从而提升推荐的相关性和吸引力。 - -## 参见 - -如需开始使用 TiDB 向量检索,请参阅以下文档: - -- [Get started with vector search using Python](/vector-search/vector-search-get-started-using-python.md) -- [Get started with vector search using SQL](/vector-search/vector-search-get-started-using-sql.md) \ No newline at end of file