Tag Archives: Batch fuzzy delete key

Python Redis: How to batch fuzzy Delete Keys

The method is as follows:

    # redis connection, chain refers to the test environment Redis environment
    r = redis.Redis(host='localhost', port=7622, db=0, decode_responses=True)

    item_list = r.keys(pattern='*app_access##qa_press_test*')
    
    # need to determine if there is a matching value, if not, it will report an error, so need to determine the processing
    if len(item_list):
        # Batch delete all cached application keys
        r.delete(*r.keys(pattern='app_access*'))
        logger.info("clear success...")
    else:
        logger.warn("with no data need to delete...")

PS: there is a detail to note here, that is, deleting directly without matching data will report an error, which needs to be handled

Note: conn.keys (‘test ‘) returns a list matching the corresponding pattern. Through the * sign, you can see that the parameters in the delete () method use variable parameters, that is, you can pass in a variable number of key values and delete them all.