4

我有一个像这样的python字典

{'OR': [{'AND': [{'column': 'XXX', 'operator': '=', 'value': u'M'}, {'column': 'XXX', 'operator': '=', 'value': 'N'}]}, {'column': 'YYY', 'operator': '>=', 'value': '3.0'}]}

现在,我想将其转换为类似

{'$or': [{'$and': [{'XXX': 'M'}, {'YYY': 'N'}]}, {'YYY': {u'$gte': 3.0}}]}

这显然是我相信的等效 pymongo 声明。

到目前为止我写的代码是这样的:

FILTMAP = {'>=': '$gte', '<=': '$lte', '>': '$gt', '<': '$lt', "!=":"$ne"}
CONJUNCTION_MAP = {"AND":"$and", "OR":"$or"}

def gen_mongo_filters_json(filter, supplied_key="")
    first_key = filters.keys()[0]
    if first_key == 'OR' or first_key == 'AND':

        if supplied_key == "":      

            return_dict[CONJUNCTION_MAP[first_key]] = []
        else:            
            temp_dict[CONJUNCTION_MAP[first_key]] = []
            #return_dict[supplied_key] = temp_dict
        for i in range (len(filters[first_key])):
            if supplied_key == "":               
                return_dict[CONJUNCTION_MAP[first_key]].append(gen_mongo_filters_json(filters[first_key][i], first_key))
            else:
                temp_dict[CONJUNCTION_MAP[first_key]].append(gen_mongo_filters_json(filters[first_key][i], first_key))
                return_dict[CONJUNCTION_MAP[supplied_key]].append(temp_dict)
    else:
        operator = filters['operator']
        if operator == "=":
            ret_dict = {filters['column']:filters['value']
            return ret_dict
        else:
            operator = FILTMAP[operator]
            ret_dict = {filters['column']:{operator:filters['value']}}
            return ret_dict
    return return_dict

它生成的输出是:

 {u'$or': [{u'$and': [{u'Engine': u'MSN'}, {u'Engine': u'Google'}]}, {u'$and': [{u'Engine': u'MSN'}, {u'Engine': u'Google'}]}, {...}, {u'Imps': {u'$gte': 3.0}}]}

这接近解决方案,但不是确切的解决方案。它适用于像

{'AND': [{'column': 'XXX', 'operator': '=', 'value': 'M'}, {'column': 'XXX', 'operator': '=', 'value': 'N'}]}

OR

{'column': 'YYY', 'operator': '>', 'value': '1000'}

你能给我指个方向吗?

(这个想法是创建一个通用的。所以,我想在 pymongo 语句中生成等效于任何有效的 python 字典。最小值是最后一个)

4

2 回答 2

3

您的示例代码没有运行,但鉴于 dict

{'OR': [{'AND': [{'column': 'XXX', 'operator': '=', 'value': 'M'}, {'column': 'YYY', 'operator': '=', 'value': 'N'}]}, {'column': 'YYY', 'operator': '>=', 'value': '3.0'}]}

应该转换为

{'$or': [{'$and': [{'XXX': 'M'}, {'YYY': 'N'}]}, {'YYY': {'$gte': 3.0}}]}

使用这样的东西:

FILTMAP = {'>=': '$gte', '<=': '$lte', '>': '$gt', '<': '$lt', "!=":"$ne"}
CONJUNCTION_MAP = {"AND":"$and", "OR":"$or"}

def convert_column(dic):
    if not dic['operator'] in FILTMAP:
        return {dic['column']: dic['value']}
    else:
        value = float(dic['value']) if dic['operator'] == "!=" else dic['value']
        return {dic['column']: {FILTMAP[dic['operator']]: value}}

def convert(dic):
    for k,v in dic.items():
        if isinstance(v, list):
            if k in CONJUNCTION_MAP:
                k = CONJUNCTION_MAP[k]
            return {k: [convert(i) for i in v]}
        else:
            return convert_column(dic)

我不知道转换'3.0'3.0. 线

value = float(dic['value']) if dic['operator'] == "!=" else dic['value']

很hackish,您想用一些适当的逻辑替换它来处理这些情况。

于 2012-10-04T12:02:59.760 回答
0

感谢你的回答。我也想通了一些事情。这是完整的代码

FILTMAP = {'>=': '$gte', '<=': '$lte', '>': '$gt', '<': '$lt', "!=":"$ne"}
CONJUNCTION_MAP = {"AND":"$and", "OR":"$or"}


def gen_mongo_filters_json(filters, supplied_key=""):
    return_dict = {}
    temp_dict = {}
    first_key = filters.keys()[0]
    if first_key == 'OR' or first_key == 'AND':

        if supplied_key == "":

            return_dict[CONJUNCTION_MAP[first_key]] = []
        else:            
            temp_dict[CONJUNCTION_MAP[first_key]] = []
            #return_dict[supplied_key] = temp_dict"""
        for i in range (len(filters[first_key])):
            if supplied_key == "":
                return_dict[CONJUNCTION_MAP[first_key]].append(gen_mongo_filters_json(filters[first_key][i], first_key))
            else:
                for i in range (len(filters[first_key])):
                    temp_dict[CONJUNCTION_MAP[first_key]].append(gen_mongo_filters_json(filters[first_key][i], first_key))
                return temp_dict
    else:
        operator = filters['operator']
        if operator == "=":
            ret_dict = {filters['column']:filters['value']}
            return ret_dict
        else:
            operator = FILTMAP[operator]
            ret_dict = {filters['column']:{operator:filters['value']}}
            return ret_dict
    return return_dict


if __name__ == "__main__":

    print gen_mongo_filters_json({'OR': [{'AND': [{'column': 'XXX', 'operator': '=', 'value': 'M'}, {'column': 'XXX', 'operator': '=', 'value': 'N'}]}, {'AND': [{'column': 'PPP', 'operator': '=', 'value': 'R'}, {'column': 'DDD', 'operator': '=', 'value': 'T'}]}]})
enter code here

请让我知道您的评论

我试过了

{'column': 'YYY', 'operator': '>', 'value': '1000'}

{'AND': [{'column': 'XXX', 'operator': '=', 'value': 'M'}, {'column': 'XXX', 'operator': '=', 'value': 'N'}]}

{'OR': [{'AND': [{'column': 'XXX', 'operator': '=', 'value': u'M'}, {'column': 'XXX', 'operator': '=', 'value': 'N'}]}, {'column': 'YYY', 'operator': '>=', 'value': '3.0'}]}

{'OR': [{'AND': [{'column': 'XXX', 'operator': '=', 'value': u'M'}, {'column': 'XXX', 'operator': '=', 'value': 'N'}]}, {'AND': [{'column': 'PPP', 'operator': '=', 'value': u'R'}, {'column': 'DDD', 'operator': '=', 'value': 'T'}]}]}

这是输出

{u'YYY': {u'$gt': u'1000'}}

{u'$and': [{u'XXX': u'M'}, {u'XXX': u'N'}]}

{u'$or': [{u'$and': [{u'XXX': u'M'}, {u'XXX': u'N'}]}, {u'YYY': {u'$gte': u'3.0'}}]}

{u'$or': [{u'$and': [{u'XXX': u'M'}, {u'XXX': u'N'}]}, {u'$and': [{u'PPP': u'R'}, {u'DDD': u'T'}]}]}

感谢你的回答。它也不错。我现在就试试。

还有一件事,我实际上在示例代码中省略了“价值”考虑。我很感谢你指出这一点。我已经有了实现这一目标的方法。不管怎么说,还是要谢谢你。

于 2012-10-04T12:37:39.887 回答