图索引模块 核心功能: 1. 为实体创建键值对(名称作为唯一索引键) 2. 为关系创建键值对(多个索引键,包含全局主题) 3. 去重和优化图操作 4. 支持增量更新
| 36 | metadata: Dict[str, Any] |
| 37 | |
| 38 | class GraphIndexingModule: |
| 39 | """ |
| 40 | 图索引模块 |
| 41 | 核心功能: |
| 42 | 1. 为实体创建键值对(名称作为唯一索引键) |
| 43 | 2. 为关系创建键值对(多个索引键,包含全局主题) |
| 44 | 3. 去重和优化图操作 |
| 45 | 4. 支持增量更新 |
| 46 | """ |
| 47 | |
| 48 | def __init__(self, config, llm_client): |
| 49 | self.config = config |
| 50 | self.llm_client = llm_client |
| 51 | |
| 52 | # 键值对存储 |
| 53 | self.entity_kv_store: Dict[str, EntityKeyValue] = {} |
| 54 | self.relation_kv_store: Dict[str, RelationKeyValue] = {} |
| 55 | |
| 56 | # 索引映射:key -> entity/relation IDs |
| 57 | self.key_to_entities: Dict[str, List[str]] = defaultdict(list) |
| 58 | self.key_to_relations: Dict[str, List[str]] = defaultdict(list) |
| 59 | |
| 60 | def create_entity_key_values(self, diseases: List[Any], symptoms: List[Any], |
| 61 | treatments: List[Any], medications: List[Any], |
| 62 | risk_factors: List[Any], care_tips: List[Any]) -> Dict[str, EntityKeyValue]: |
| 63 | """ |
| 64 | 为实体创建键值对结构 |
| 65 | 每个实体使用其名称作为唯一索引键 |
| 66 | """ |
| 67 | logger.info("开始创建实体键值对...") |
| 68 | |
| 69 | label_display = { |
| 70 | "Disease": "疾病", |
| 71 | "Symptom": "症状", |
| 72 | "Treatment": "治疗方案", |
| 73 | "Medication": "药物", |
| 74 | "RiskFactor": "风险因素", |
| 75 | "CareTip": "护理建议" |
| 76 | } |
| 77 | |
| 78 | def _store_entity(entity_list, entity_label, aliases=None): |
| 79 | for entity in entity_list: |
| 80 | entity_id = entity.node_id |
| 81 | entity_name = entity.name or f"{entity_label}_{entity_id}" |
| 82 | |
| 83 | props = getattr(entity, "properties", {}) |
| 84 | display_label = label_display.get(entity_label, entity_label) |
| 85 | content_parts = [f"{display_label}名称: {entity_name}"] |
| 86 | if props.get("description"): |
| 87 | content_parts.append(f"描述: {props['description']}") |
| 88 | if props.get("category"): |
| 89 | content_parts.append(f"分类: {props['category']}") |
| 90 | if props.get("severity"): |
| 91 | content_parts.append(f"严重程度: {props['severity']}") |
| 92 | if props.get("tags"): |
| 93 | content_parts.append(f"标签: {props['tags']}") |
| 94 | if props.get("methods"): |
| 95 | content_parts.append(f"方法: {props['methods']}") |