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