'Ensure if an index with mapping exists'

def ensure_index(self, index, mappings=None, settings=None, clear=False):

    mappings = (mappings or [])
    if isinstance(mappings, dict):
        mappings = [mappings]
    exists = self.indices.exists_index(index)
    if (exists and (not mappings) and (not clear)):
        return
    if (exists and clear):
        self.indices.delete_index(index)
        exists = False
    if exists:
        if (not mappings):
            self.indices.delete_index(index)
            self.indices.refresh()
            self.indices.create_index(index, settings)
            return
        if clear:
            for maps in mappings:
                for key in list(maps.keys()):
                    self.indices.delete_mapping(index, doc_type=key)
            self.indices.refresh()
        if isinstance(mappings, SettingsBuilder):
            for (name, data) in list(mappings.mappings.items()):
                self.indices.put_mapping(doc_type=name, mapping=data, indices=index)
        else:
            from pyes.mappings import DocumentObjectField, ObjectField
            for maps in mappings:
                if isinstance(maps, tuple):
                    (name, mapping) = maps
                    self.indices.put_mapping(doc_type=name, mapping=mapping, indices=index)
                elif isinstance(maps, dict):
                    for (name, data) in list(maps.items()):
                        self.indices.put_mapping(doc_type=name, mapping=maps, indices=index)
                elif isinstance(maps, (DocumentObjectField, ObjectField)):
                    self.put_mapping(doc_type=maps.name, mapping=maps.as_dict(), indices=index)
            return
    if settings:
        if isinstance(settings, dict):
            settings = SettingsBuilder(settings, mappings)
    elif isinstance(mappings, SettingsBuilder):
        settings = mappings
    else:
        settings = SettingsBuilder(mappings=mappings)
    if (not exists):
        self.indices.create_index(index, settings)
        self.indices.refresh(index, timesleep=1)
