query parser

12 09 2007

this function will make a line like this

“hello world” +text:hello -title:world value fun

to a array like this

(title:”hello world” or text:”hello world”) or (title:value or text:value) or (title: fun or text:fun) +text:hello -title:world

It is good for i.e lucene search.

internal string CreateLuceneQuery(string input,string[] fields)
{
    return BuildQuery(fields,GetAllQueryWord(input));
}
internal string[] GetAllQueryWord(string input)
{
    ArrayList ar = new ArrayList();
    Regex reg = new Regex(“[\”]([^\”]*)[\”]”,RegexOptions.Singleline | RegexOptions.IgnoreCase);
    MatchCollection mc =  reg.Matches(input);

    foreach (Match m in mc)
    {
        ar.Add(m.Groups[0].ToString());
    }
    string remain = input;
    foreach (string s in ar)
    {
        remain = remain.Replace(s,””);
    }
    string[] normalstring = remain.Split(new char[]{‘ ‘});
    ar.AddRange(normalstring);

    ArrayList retAr = new ArrayList();
    foreach (string s in ar)
    {
        if (s!=””)
            retAr.Add(s);
    }
    return (string[]) retAr.ToArray(typeof(string));
}

internal string BuildQuery(string[] fields,string[] conditions)
{
    string q = “”;
    foreach ( string condition in conditions)
    {
        string s = condition;
        if (s.StartsWith(“+”))
        {
            q+=” +”;
            s = s.Substring(1);
        }
        else
        {
            if (s.StartsWith(“-“))
            {
                q+=” -“;
                s = s.Substring(1);
            }
            else
            {
                if (q!=””)
                    q+=” or “;
            }
        }

        if (s.IndexOf(“:”)>0)
        {
            q+=s;
        }
        else
        {
            q+=”(“;
            string qbuild = “”;
            foreach (string field in fields)
            {
                if (qbuild != “”)
                    qbuild+=” or “;
                qbuild+=field+”:”+s;
            }
            q+=qbuild;
            q+=”)”;
        }
    }
    return q;
}

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: