from django.core.management import BaseCommand
from libs.es import es_query
from django.conf import settings
from datetime import datetime
from libs.date import datetime_to_timestamp_millis
from libs.debug import pretty_json
from libs.cache import redis_client
from extend.models.gaia import WordRel,WordRelSynonym,WordRelResemble
import logging
import traceback
import json

class Command(BaseCommand):

    def handle(self, *args, **options):
        try:
            all_word_rel_key = "doris:total_keywords"
            key_word_synonym_key = "doris:key_word_synonym"

            keyword_results = WordRel.objects.all()

            all_key_word_set = set()
            for key_word_obj in keyword_results:
                key_word_obj.keyword = key_word_obj.keyword.strip()
                item_list = key_word_obj.keyword.split("、")
                for item in item_list:
                    item = item.strip()
                    if item:
                        all_key_word_set.add(item)

                synonym_set = set()
                synonym_data_list = key_word_obj.all_synonyms.all().values_list("word",flat=True)
                for data in synonym_data_list:
                    item_list = data.split("、")
                    for item in item_list:
                        item = item.strip()
                        if item:
                            synonym_set.add(item)
                if len(synonym_set)>0:
                    redis_client.hset(key_word_synonym_key,key_word_obj.keyword,json.dumps(list(synonym_set)))

            redis_client.set(all_word_rel_key,json.dumps(list(all_key_word_set)))


        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
