#!/usr/bin/env python
# -*- coding:utf-8 -*-

from whoosh.filedb.filestore import FileStorage
from whoosh.index import FileIndex
from whoosh.writing import AsyncWriter
from decimal import Decimal
import pymysql



def update_index(indexdir, indexname, Data):
    """
    注意这里，　每次增加索引都会产生一个新的ｓｅｇ文件，　会占用空间，　所以这里需要注意
    :param indexdir:  索引目录
    :param indexname: 索引名
    :return:
    """
    # print(indexdir)

    storage = FileStorage(indexdir)
    ix = FileIndex(storage, indexname=indexname)

    writer = AsyncWriter(ix)

    # writer.update_document(content="人在塔在===加了修改", ID="hik")
    docline = """writer.update_document("""

    for key in Data:
        val = Data[key]
        if not val:
            val = ""
        elif isinstance(val, (Decimal,)):
            val = str(val)
        else:
            val = pymysql.escape_string(str(val))
        docline += key + '="' + val + '", '
    docline = docline.rstrip(", ")
    docline += """)"""
    eval(docline)

    writer.commit()