def apply(self, doc, clear, **kwargs):
<EOL>doc = self.session.merge(doc)<EOL>for i, mention_class in enumerate(self.mention_classes):<EOL><INDENT>tc_to_insert = defaultdict(list)<EOL>self.child_context_set.clear()<EOL>for tc in self.matchers[i].apply(self.mention_spaces[i].apply(doc)):<EOL><INDENT>rec = tc._load_id_or_insert(self.session)<EOL>if rec:<EOL><INDENT>tc_to_insert[tc._get_table()].append(rec)<EOL><DEDENT>self.child_context_set.add(tc)<EOL><DEDENT>for table, records in tc_to_insert.items():<EOL><INDENT>stmt = insert(table.__table__).values(records)<EOL>self.session.execute(stmt)<EOL><DEDENT>mention_args = {"<STR_LIT>": doc.id}<EOL>for child_context in self.child_context_set:<EOL><INDENT>for arg_name in mention_class.__argnames__:<EOL><INDENT>mention_args[arg_name + "<STR_LIT>"] = child_context.id<EOL><DEDENT>if not clear:<EOL><INDENT>q = select([mention_class.id])<EOL>for key, value in list(mention_args.items()):<EOL><INDENT>q = q.where(getattr(mention_class, key) == value)<EOL><DEDENT>mention_id = self.session.execute(q).first()<EOL>if mention_id is not None:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>yield mention_class(**mention_args)<EOL><DEDENT><DEDENT>
Extract mentions from the given Document.

        :param doc: A document to process.
        :param clear: Whether or not to clear the existing database entries.