def escape_for_lucene(query: str) -> str:
  """Reimplementation of QueryParser.escape.

  See
  https://github.com/apache/lucene-solr/blob/d894a7e8d75967fd0574bc1c98860b6062c21773/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java#L971

  Args:
    query:  Query string.

  Returns:
    Properly escaped version of query.
  """
  result_buffer = []
  for c in query:
    # These characters are part of the query syntax and must be escaped.
    if (c == '\\' or c == '+' or c == '-' or c == '!' or c == '(' or c == ')' or
        c == ':' or c == '^' or c == '[' or c == ']' or c == '\"' or c == '{' or
        c == '}' or c == '~' or c == '*' or c == '?' or c == '|' or c == '&' or
        c == '/'):
      result_buffer.append('\\')
    result_buffer.append(c)

  return ''.join(result_buffer)