Default value of a field?

Issue #381 resolved
created an issue

This not a bug. Just don't understand how to deal it.


When user not assign a value to a special field. I want the special field be assigned a default value. for example:

  • user input: apple == apple type:fruit
  • user input: apple type:red == apple type:red

I think it maybe need to write a simply qparser.Plugin but I still don't know how to do it.

Can you give me a example? Or any help?

Very thanks!

My Search Code

import whoosh.qparser as WQ
import whoosh.highlight as WH

def index_search(query_string):
    """Get search results from user's input"""
    ix = WI.open_dir(INDEX_DIR)
    with ix.searcher() as searcher:
        # Configure a QueryParser
        qp = WQ.QueryParser("text", INDEX_SCHEMA)
        # Add two plugins
        qp.add_plugin(WQ.MultifieldPlugin(["text", "pname", "pdesc"]))
        # generate query by user's input
        query = qp.parse(query_string)
        # real searching...
        results =, limit = 20, terms=True)

        results.fragmenter = WH.PinpointFragmenter(autotrim = True)
        return generate_html_from_template("data-search.html", results = results)

Comments (3)

  1. Matt Chaput repo owner

    Ooh, good question. It's complicated because if you're using the default query parser you can have arbitrary query trees like

    ((apple OR pear) AND (NOT type:tropical)) OR ((banana OR mango) AND type:new)

    However, if you're OK with saying that if the query has any term in the "type" field then you'll turn off the "default", then the simplest way is probably to just inspect and modify the parsed query:

    # Parse the user query
    q = qp.parse(myquery)
    # Iterate over all term queries in the query tree, see if any of them
    # are in the "type" field
    hastype = False
    for fieldname, text in q.iter_all_terms():
      if fieldname == "type":
        hastype = True
    # If the query has no terms in the "type" field, add a default type term
    if not hastype:
      # Create a term query, AND it together with the original query,
      # and call normalize() to tidy up the new query
      q = query.And(q, query.Term("type", u"fruit")).normalize()
  2. visig reporter

    Wow! You are right... It more complex than I thought before.

    I will reconsider implement or not.

    And thanks your nice example! (^_^)/

  3. Log in to comment