// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Data; using Npgsql; namespace TextSearch.Rdbms.PgSQL.Search { public class Program { private static void Dump0(IDbCommand cmd, string searchtype) { Console.WriteLine("{0}", searchtype); using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Console.WriteLine(" {0} - {1}", (string)dr["names"], (string)dr["moves"]); } } } private static void Dump1(IDbCommand cmd, string searchtype, string searchterm) { Console.WriteLine("{0} search for : {1}", searchtype, searchterm); ((IDbDataParameter)cmd.Parameters["@st"]).Value = searchterm; using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Console.WriteLine(" {0} - {1}", (string)dr["names"], (string)dr["moves"]); } } } public static void Main(string[] args) { using (IDbConnection con = new NpgsqlConnection("Host=localhost;Database=Test;Username=postgres;Password=hemmeligt")) { con.Open(); // all using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT names,moves FROM chessopening"; Dump0(cmd, "all"); } // one using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT names, moves FROM chessopening WHERE TO_TSVECTOR(names) @@ TO_TSQUERY (@st)"; IDbDataParameter st = cmd.CreateParameter(); st.ParameterName = "@st"; st.DbType = DbType.String; cmd.Parameters.Add(st); Dump1(cmd, "one", "defense"); } using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT names, moves FROM chessopening WHERE TO_TSVECTOR(moves) @@ TO_TSQUERY (@st)"; IDbDataParameter st = cmd.CreateParameter(); st.ParameterName = "@st"; st.DbType = DbType.String; cmd.Parameters.Add(st); Dump1(cmd, "one", "d4"); } // dual using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT names, moves FROM chessopening WHERE TO_TSVECTOR(names || ' ' || moves) @@ TO_TSQUERY (@st)"; IDbDataParameter st = cmd.CreateParameter(); st.ParameterName = "@st"; st.DbType = DbType.String; cmd.Parameters.Add(st); Dump1(cmd, "dual", "defense"); Dump1(cmd, "dual", "d4"); Dump1(cmd, "dual", "defense | d4"); // or Dump1(cmd, "dual", "defense & d4"); // and Dump1(cmd, "dual", "defense & !d4"); // not Dump1(cmd, "dual", "def:*"); // wildcard Dump1(cmd, "dual", "N:*"); // wildcard } } } } }