線上問診 Python、FastAPI、Neo4j — 生成 Cypher 語句

VipSoft發表於2023-09-28


這邊只是為了測試,演示效果和思路,實際應用中,可以透過NLP構建CQL
接上一篇的問題分類

question = "請問最近看東西有時候清楚有時候不清楚是怎麼回事"
# 最終輸出
data = {'args': {'看東西有時候清楚有時候不清楚': ['symptom']}, 'question_types': ['symptom_disease']}

question = "乾眼常用藥有哪些"
# 最終輸出
data = {'args': {'乾眼': ['disease']}, 'question_types': ['disease_drug']}

question = "乾眼哪些不能吃"
data = {'args': {'乾眼': ['disease']}, 'question_types': ['disease_not_food']}

構建節點字典

目的,為了拼CQL,查出符合條件的節點詳情

def build_nodedict(self, args):
    """
    構建節點字典
    :param args: {'看東西有時候清楚有時候不清楚': ['symptom']}
    :return: 組裝成 => {'symptom': '看東西有時候清楚有時候不清楚'}
    """
    node_dict = {}
    for arg, types in args.items():
        for type in types:
            if type not in node_dict:
                node_dict[type] = [arg]
            else:
                node_dict[type].append(arg)
    return node_dict
# 輸入:
{'看東西有時候清楚有時候不清楚': ['symptom']}
# 輸出:
{'symptom': ['看東西有時候清楚有時候不清楚']}

構建Cypher CQL語句

# 查詢症狀會導致哪些疾病
if question_type == 'symptom_disease':
    sql = ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities]

# 查詢症狀會導致哪些疾病
if question_type == 'symptom_disease':
    sql = ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities]

# 查詢疾病常用藥品-藥品別名記得擴充
if question_type == 'disease_drug':
    sql = ["MATCH (m:Disease)-[r:used_drugs]->(n:Drug) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities]


# 查詢疾病的忌口
if question_type == 'disease_not_food':
    sql = ["MATCH (m:Disease)-[r:noteat_foods]->(n:Foods) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities]

node_dict.get('symptom')

Test

if __name__ == '__main__':
    handler = QuestionPaser()
    question_class = {'args': {'看東西有時候清楚有時候不清楚': ['symptom']}, 'question_types': ['symptom_disease']}
    cql = handler.parser_main(question_class)
    print(cql)

輸出:

# 輸入
question_class = {'args': {'看東西有時候清楚有時候不清楚': ['symptom']}, 'question_types': ['symptom_disease']}
# 輸出
[{'question_type': 'symptom_disease', 'sql': ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '看東西有時候清楚有時候不清楚' return m.name, r.name, n.name"]}]

# 輸入:
question_class = {'args': {'乾眼': ['disease']}, 'question_types': ['disease_drug']}
# 輸出: 
[{'question_type': 'disease_drug', 'sql': ["MATCH (m:Disease)-[r:used_drugs]->(n:Drug) where m.name = '乾眼' return m.name, r.name, n.name"]}]

# 輸入:
question_class = {'args': {'乾眼': ['disease']}, 'question_types': ['disease_not_food']}
# 輸出:
[{'question_type': 'disease_not_food', 'sql': ["MATCH (m:Disease)-[r:noteat_foods]->(n:Foods) where m.name = '乾眼' return m.name, r.name, n.name"]}]

image

後面根據 生成的 CQL語句,查詢出知識圖譜中對應的資料,

原始碼地址:https://gitee.com/VipSoft/VipQA

相關文章