002_candidate_items_unique_key.sql 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. -- 002: add formal candidate item unique_key.
  2. -- Applied to database: creation_knowledge_prod
  3. ALTER TABLE creation_knowledge.candidate_items
  4. ADD COLUMN IF NOT EXISTS unique_key text;
  5. WITH extracted AS (
  6. SELECT
  7. id,
  8. platform,
  9. COALESCE(
  10. NULLIF(platform_item_id, ''),
  11. NULLIF(source_payload #>> '{candidate,source_id}', ''),
  12. NULLIF(source_payload #>> '{detail,data,data,channel_content_id}', ''),
  13. NULLIF(substring(canonical_url from '/explore/([^/?#]+)'), '')
  14. ) AS xhs_id,
  15. COALESCE(
  16. NULLIF(platform_item_id, ''),
  17. NULLIF(source_payload #>> '{candidate,source_id}', ''),
  18. NULLIF(source_payload #>> '{candidate,raw,id}', ''),
  19. NULLIF(source_payload #>> '{detail,data,data,channel_content_id}', ''),
  20. NULLIF(substring(canonical_url from '/video/([^/?#]+)'), '')
  21. ) AS dy_id,
  22. substring(canonical_url from '[?&]__biz=([^&#]+)') AS wx_biz,
  23. substring(canonical_url from '[?&]mid=([^&#]+)') AS wx_mid,
  24. substring(canonical_url from '[?&]idx=([^&#]+)') AS wx_idx,
  25. substring(canonical_url from '[?&]sn=([^&#]+)') AS wx_sn
  26. FROM creation_knowledge.candidate_items
  27. WHERE unique_key IS NULL
  28. )
  29. UPDATE creation_knowledge.candidate_items ci
  30. SET unique_key = CASE
  31. WHEN e.platform = 'xiaohongshu' AND e.xhs_id IS NOT NULL THEN 'xhs:' || e.xhs_id
  32. WHEN e.platform = 'douyin' AND e.dy_id IS NOT NULL THEN 'dy:' || e.dy_id
  33. WHEN e.platform = 'weixin'
  34. AND e.wx_biz IS NOT NULL
  35. AND e.wx_mid IS NOT NULL
  36. AND e.wx_idx IS NOT NULL
  37. AND e.wx_sn IS NOT NULL
  38. THEN 'wx:' || e.wx_biz || ':' || e.wx_mid || ':' || e.wx_idx || ':' || e.wx_sn
  39. ELSE NULL
  40. END
  41. FROM extracted e
  42. WHERE ci.id = e.id;
  43. CREATE UNIQUE INDEX IF NOT EXISTS idx_candidate_items_unique_key
  44. ON creation_knowledge.candidate_items(unique_key)
  45. WHERE unique_key IS NOT NULL;
  46. INSERT INTO creation_knowledge.schema_migrations(version, description)
  47. VALUES ('002_candidate_items_unique_key', 'Add candidate_items.unique_key and backfill existing candidate identities')
  48. ON CONFLICT (version) DO UPDATE
  49. SET description = EXCLUDED.description,
  50. applied_at = now();