Files
akmon/doc_news/INDEX_ERROR_SOLUTION.md
2026-01-20 08:04:15 +08:00

108 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 数据库索引错误解决方案
当出现 `ERROR: 42P07: relation "idx_content_sources_type" already exists` 错误时,说明索引已经存在。有以下几种解决方案:
## 方案1删除现有索引推荐
在PostgreSQL中执行以下命令
```sql
-- 删除所有可能已存在的索引
DROP INDEX IF EXISTS public.idx_content_sources_type;
DROP INDEX IF EXISTS public.idx_content_sources_language;
DROP INDEX IF EXISTS public.idx_content_sources_active;
DROP INDEX IF EXISTS public.idx_raw_contents_source;
DROP INDEX IF EXISTS public.idx_raw_contents_hash;
DROP INDEX IF EXISTS public.idx_raw_contents_status;
DROP INDEX IF EXISTS public.idx_raw_contents_language;
DROP INDEX IF EXISTS public.idx_raw_contents_published;
DROP INDEX IF EXISTS public.idx_raw_contents_quality;
```
然后重新运行主数据库脚本。
## 方案2跳过索引创建错误
在psql中设置
```sql
\set ON_ERROR_STOP off
```
然后运行主脚本,它会跳过已存在的索引创建错误。
## 方案3完全重建数据库
如果是开发环境,可以完全重建:
```sql
-- 警告:这会删除所有数据!
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
```
然后运行主数据库脚本。
## 方案4检查现有索引
检查哪些索引已经存在:
```sql
SELECT indexname, tablename
FROM pg_indexes
WHERE schemaname = 'public'
AND indexname LIKE 'idx_%'
ORDER BY tablename, indexname;
```
## 推荐操作步骤
1. 首先检查现有索引:
```bash
psql -U username -d database_name -c "SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND indexname LIKE 'idx_%';"
```
2. 如果有冲突的索引,删除它们:
```bash
psql -U username -d database_name -c "DROP INDEX IF EXISTS public.idx_content_sources_type;"
```
3. 重新运行主数据库脚本:
```bash
psql -U username -d database_name -f ai_multilingual_news_database.sql
```
## 自动化解决脚本
创建一个简单的bash脚本
```bash
#!/bin/bash
DB_NAME="your_database"
DB_USER="your_user"
echo "清理现有索引..."
psql -U $DB_USER -d $DB_NAME -c "
DO \$\$
DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT indexname FROM pg_indexes WHERE indexname LIKE 'idx_%' AND schemaname = 'public')
LOOP
EXECUTE 'DROP INDEX IF EXISTS public.' || quote_ident(r.indexname);
END LOOP;
END \$\$;
"
echo "运行主数据库脚本..."
psql -U $DB_USER -d $DB_NAME -f ai_multilingual_news_database.sql
echo "完成!"
```
保存为 `deploy_database.sh` 并运行:
```bash
chmod +x deploy_database.sh
./deploy_database.sh
```