Exemple #1
0
        public void Query_InvalidField_ShouldNOTThrow()
        {
            const string response =
                @"<?xml version=""1.0"" encoding=""UTF-8""?>
<response>
<lst name=""responseHeader""><int name=""status"">0</int><int name=""QTime"">0</int><lst name=""params""><str name=""q"">id:123456</str><str name=""?""/><str name=""version"">2.2</str></lst></lst><result name=""response"" numFound=""1"" start=""0""><doc><str name=""advancedview""/><str name=""basicview""/><int name=""id"">123456</int></doc></result>
</response>";
            var conn = new MSolrConnection();

            conn.get       &= x => x.Return(response);
            Solr.Connection = conn;
            Solr.Query <TestDocument>("");
        }
Exemple #2
0
        public void OrderBy2()
        {
            const string queryString = "id:123";
            var          query       = new Dictionary <string, string> {
                { "q", queryString },
                { "rows", DefaultRows() },
                { "sort", "id asc" },
            };
            var conn = new MockConnection(query);

            Solr.Connection = conn;
            Solr.Query <TestDocument>(new SolrQuery(queryString), new SortOrder("id", Order.ASC));
        }
Exemple #3
0
        public void QueryISolrQueryWithPagination()
        {
            const string queryString = "id:123";
            var          query       = new Dictionary <string, string> {
                { "q", queryString },
                { "start", 10.ToString() },
                { "rows", 20.ToString() }
            };
            var conn = new MockConnection(query);

            Solr.Connection = conn;
            Solr.Query <TestDocument>(new SolrQuery(queryString), 10, 20);
        }
Exemple #4
0
        public void Highlighting()
        {
            var conn = new MockConnection(new Dictionary <string, string> {
                { "q", "(makedesc:(bmw))" },
                { "hl", "true" },
                { "hl.fl", "make" },
                { "rows", DefaultRows() },
            });

            Solr.Connection = conn;
            var r = Solr.Query <TestDocument>().By("makedesc").Is("bmw").WithHighlighting(new HighlightingParameters {
                Fields = new[] { "make" },
            }).Run();
        }
Exemple #5
0
        public void OrderBy()
        {
            var conn = new MockConnection(new Dictionary <string, string> {
                { "q", "(Id:(123456))" },
                { "sort", "id asc" },
                { "rows", DefaultRows() },
            });

            Solr.Connection = conn;
            Solr.Query <TestDocumentWithId>()
            .By("Id").Is("123456")
            .OrderBy("id")
            .Run();
        }
Exemple #6
0
        public void FacetQuery_ISolrQuery()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks)
            .Expecting(() => Expect.Call(conn.Get(null, null))
                       .IgnoreArguments()
                       .Repeat.Once()
                       .Return(response))
            .Verify(() => {
                Solr.Connection = conn;
                var r           = Solr.Query <TestDocument>().By("makedesc").Is("bmw").WithFacetQuery(new SolrQuery("")).Run();
            });
        }
Exemple #7
0
        public void QueryByExample()
        {
            var query = new Dictionary <string, string> {
                { "q", "(Id:123456)" },
                { "rows", DefaultRows() },
            };
            var conn = new MockConnection(query);

            Solr.Connection = conn;
            var doc = new TestDocumentWithId {
                Id = 123456
            };

            Solr.Query <TestDocumentWithId>().By("Id").Is("123456").Run();
        }
Exemple #8
0
        public void FacetField_options()
        {
            var conn = new MSolrConnection();

            conn.get       &= x => x.Return(response);
            Solr.Connection = conn;
            var r = Solr.Query <TestDocument>().By("makedesc").Is("bmw")
                    .WithFacetField("modeldesc")
                    .LimitTo(100)
                    .DontSortByCount()
                    .WithPrefix("xx")
                    .WithMinCount(10)
                    .StartingAt(20)
                    .IncludeMissing()
                    .Run();
        }
Exemple #9
0
        public void QueryWithPagination()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks)
            .Expecting(() => Expect.Call(conn.Get(null, null))
                       .IgnoreArguments()
                       .Repeat.Once()
                       .Return(response))
            .Verify(() => {
                Solr.Connection = conn;
                var r           = Solr.Query <TestDocument>("", 10, 20);
                Assert.AreEqual(1, r.NumFound);
            });
        }
Exemple #10
0
        public void Query_InvalidField_ShouldNOTThrow()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks)
            .Expecting(() => Expect.Call(conn.Get(null, null)).IgnoreArguments().Repeat.Once().Return(
                           @"<?xml version=""1.0"" encoding=""UTF-8""?>
<response>
<lst name=""responseHeader""><int name=""status"">0</int><int name=""QTime"">0</int><lst name=""params""><str name=""q"">id:123456</str><str name=""?""/><str name=""version"">2.2</str></lst></lst><result name=""response"" numFound=""1"" start=""0""><doc><str name=""advancedview""/><str name=""basicview""/><int name=""id"">123456</int></doc></result>
</response>
"))
            .Verify(() => {
                Solr.Connection = conn;
                Solr.Query <TestDocument>("");
            });
        }
Exemple #11
0
        public void OrderByAscDesc()
        {
            var query = new Dictionary <string, string> {
                { "q", "(Id:(123456))" },
                { "rows", DefaultRows() },
                { "sort", "id asc" },
            };
            var conn = new MockConnection(query);

            Solr.Connection = conn;
            var doc = new TestDocumentWithId {
                Id = 123456
            };

            Solr.Query <TestDocumentWithId>()
            .By("Id").Is("123456")
            .OrderBy("id", Order.ASC)
            .Run();
        }
Exemple #12
0
        public void FacetField_options()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks)
            .Expecting(() => Expect.Call(conn.Get(null, null))
                       .IgnoreArguments()
                       .Repeat.Once()
                       .Return(response))
            .Verify(() => {
                Solr.Connection = conn;
                var r           = Solr.Query <TestDocument>().By("makedesc").Is("bmw")
                                  .WithFacetField("modeldesc")
                                  .LimitTo(100)
                                  .DontSortByCount()
                                  .WithPrefix("xx")
                                  .WithMinCount(10)
                                  .StartingAt(20)
                                  .IncludeMissing()
                                  .Run();
            });
        }
Exemple #13
0
        //public String GetBaseUri(HttpRequestBase req, UrlHelper url_helper)
        //{
        //    if (req.Url != null)
        //    {
        //        return string.Format("{0}://{1}{2}", req.Url.Scheme, req.Url.Authority, url_helper.Content("~"));
        //    }

        //    LogHelper.StatsLog(null, "GetBaseUri()", String.Format("Failed, request is null!"), null, null);
        //    return "http://localhost/";
        //}

        // public abstract SolrSearchResults Search(string term, List<string> ids, int rows, int row_start, string parent_id, List<SortField> sort_orders, List<KeyValuePair<string, string>> facet_constraints, List<KeyValuePair<string, string>> facets, List<FacetRange> facet_ranges);
        // public abstract SolrSearchResults GetRecord(string id);
        // public abstract SolrSearchResults GetSearchSuggestions(string str);


        public virtual SolrSearchResults Search(SearchQuery query, List <KeyValuePair <string, string> > facets, List <FacetRange> facet_ranges)
        {
            // string solr_term = (ids.Count > 0) ? String.Format("{0}:^", _solrIdField) : makeSolrTerm(term, ids);
            string solr_term = makeSolrTerm(query.Term, query.IDs);

            //if (String.IsNullOrEmpty(query.ParentID))
            //    solr_term = String.Format("{0} AND -{1}:[* TO *]", solr_term, ParentIdFieldName);
            //else
            //    solr_term = String.Format("{0} AND {1}:{2}", solr_term, ParentIdFieldName, query.ParentID);

            if (String.IsNullOrEmpty(query.ParentID))
            {
                solr_term = String.Format("{0} AND -{1}:[* TO *]", solr_term, ParentIdFieldName);
            }
            else
            {
                solr_term = String.Format("{0} AND {1}:{2}", solr_term, ParentIdFieldName, query.ParentID);
            }


            #region facet constraints
            var str = new StringBuilder();
            var i   = 0;
            foreach (FacetConstraint f in query.FacetConstraints) // KeyValuePair<string, List<string>>
            {
                int j = 0;
                str.Append("(");

                foreach (string val in f.Constraints)
                {
                    if (val.Contains(" to "))
                    {
                        // facet range, need to convert user friendly name sent by ajax back to correct db field name, if needed
                        var fn = f.Field;
                        foreach (FacetRange fr in facet_ranges)
                        {
                            if (fn == fr.DisplayName)
                            {
                                fn = fr.Field;
                                break;
                            }
                        }
                        // iterate over string list of values here, for multi valued constraints same key = OR, when going to different key AND
                        // if not multi valued constraints then always AND?
                        str.Append(String.Format("{0}:[{1}]", fn.Replace(":", @"\:"), val.ToUpper())); // str.Append("DateStartYear:[1800 TO 1900]");
                    }
                    else
                    {
                        str.Append(String.Format("{0}:{1}{2}{3}", f.Field.Replace(":", @"\:"), "\"", val, "\""));
                    }

                    j++;
                    if (j != f.Constraints.Count)
                    {
                        str.Append(" OR ");
                    }
                    else
                    {
                        str.Append(")");
                    }
                }

                i++;
                if (i != query.FacetConstraints.Count)
                {
                    //if(MultiFacetConstraints)
                    //    str.Append(" OR ");
                    //else
                    str.Append(" AND ");
                }
            }

            var d = new Dictionary <string, string> {
                { "fq", str.ToString() }, { "facet.sort", "count" }
            };                                                                                              // ordering of the facets
            #endregion

            #region search term highlighting
            if (!String.IsNullOrEmpty(query.Term)) // if user has entered a search term then we want highlighting of that term in the results, if not we don't want it as adds overheads
            {
                d.Add("hl", "on");
                d.Add("hl.fl", "*");
                // d.Add("hl.fragsize", "0");
            }
            #endregion search term highlighting

            #region facet queries
            // only needed if not multi facet constraints, as multi facet constraints are enabled then we don't need to refine the
            // available facets with the search (ie only return facets applicable to the search, the list obtained once at the start
            // remains valid, so no point adding overheads to this query
            // NB: if we are requesting 0 rows of results then this must be a request just for facet data, so in this case add the facet params
            var facet = new FacetParameters();
            facet.Limit = FacetLimit;

            if ((MultiFacetConstraints == false) || (query.Rows == 0))
            {
                var queries = new List <ISolrFacetQuery>();
                foreach (KeyValuePair <string, string> kvp in facets) // these come from the app config
                {
                    queries.Add(new SolrFacetFieldQuery(kvp.Key));
                }

                // have to use the slightly crude method below as Facet by Range is in Solr 3.1+ but not exposed by solrnet
                // see no FaceRanges property exposed by Solr results object
                // Would want to use following: &facet.range=DateStartYear&f.DateStartYear.facet.range.start=1000&f.DateStartYear.facet.range.end=2100&f.DateStartYear.facet.range.gap=50
                // Full query: http://armserv:8080/solr/core1/select?facet=true&facet.sort=count&start=0&q=*:*+AND+-ParentNodes:[*+TO+*]&?=&fq=&rows=0&facet.field=Genre&facet.range=DateStartYear&f.DateStartYear.facet.range.start=1000&f.DateStartYear.facet.range.end=2100&f.DateStartYear.facet.range.gap=50

                foreach (FacetRange fr in facet_ranges) // these need to come from the app config
                {
                    if (fr.WildcardLower)
                    {
                        queries.Add(new SolrFacetQuery(new SolrQueryByRange <string>(fr.Field, "*", (fr.From - 1).ToString())));
                    }

                    for (int y = fr.From; y < fr.To; y = y + fr.Gap)
                    {
                        queries.Add(new SolrFacetQuery(new SolrQueryByRange <string>(fr.Field, y.ToString(), (y + (fr.Gap - 1)).ToString())));
                    }

                    if (fr.WildcardUpper)
                    {
                        queries.Add(new SolrFacetQuery(new SolrQueryByRange <string>(fr.Field, (fr.To + 1).ToString(), "*")));
                    }
                }

                facet.Queries = queries;
            }
            #endregion

            #region sort orders
            var order_by = new List <SortOrder>();
            foreach (SortField sf in query.SortFields)
            {
                SortOrder so;

                if (sf.DbField == "Random")
                {
                    so = new RandomSortOrder("randomF");
                }
                else
                {
                    var order = Order.ASC;
                    if (sf.SortDirection.ToLower() == "desc")
                    {
                        order = Order.DESC;
                    }
                    so = new SortOrder(sf.DbField, order);
                }

                order_by.Add(so);
            }
            #endregion sort orders

            // i think the below could be put in super classes, and makeSolrSearchResults changed to accept the disassembled properties of the specific IInqItem implementation
            #region ninject approach doesn't work, get "can't create instance of interface" error?

            /*using (IKernel kernel = new StandardKernel(new SolrNetModule(_solrUri)))
             * {
             *  var solr = kernel.Get<ISolrOperations<IInqItem>>();
             *  try
             *  {
             *      var results = solr.Query(new SolrQuery(solr_term), new QueryOptions { Rows = rows, Start = row_start, Facet = facet, OrderBy = order_by, ExtraParams = d });
             *      return makeSolrSearchResults(results, facets, facet_ranges);
             *  }
             *  catch (Exception e)
             *  {
             *      throw new Exception("Fatal error, could not perform search, Solr not responding?: " + e.Message);
             *  }
             * }*/
            #endregion

            // var solr = ServiceLocator.Current.GetInstance<ISolrOperations<InqItemArmNode>>();
            // var solr = ServiceLocator.Current.GetInstance<ISolrOperations<InqItemBod>>();

            //try
            //{
            var results = Solr.Query(new SolrQuery(solr_term), new QueryOptions
            {
                Rows        = query.Rows,
                Start       = query.RowStart,
                Facet       = facet,
                OrderBy     = order_by,
                ExtraParams = d
            });
            return(makeSolrSearchResults(results, facets, facet_ranges));
            //}
            //catch (Exception e)
            //{
            //    throw new Exception("Fatal error, could not perform search, Solr not responding or failed to create results?: " + e.Message);
            //}
        }