/// <summary>
 /// 建立連接并獲取符合條件的idList
 /// GetIdList獲取查詢框對應的idList
 /// GetFlagList獲取食安關鍵字對應的idList
 /// GetSphinxExcludeIdList獲取要排除的idList
 /// </summary>
 /// <param name="query"></param>
 public List<int> GetIdList(string key,int MaxMatches)
 {
     List<int> idList = new List<int>();
     using (TcpConnection connection = new PersistentTcpConnection(_sphinxHost, _sphinxPort))
     {
        
         try
         {
             ///獲得全部要搜索的關鍵字
             SearchCommand search = new SearchCommand(connection);
             ///綁定搜索關鍵字
             SearchQuery searchQuery = new SearchQuery(key);
             searchQuery.Limit = searchQuery.MaxMatches = MaxMatches;
             search.QueryList.Add(searchQuery);
             search.Execute();
             if (search.Result.Status == CommandStatus.Warning)
             {
                 foreach (var s in search.Result.Warnings)
                 {
                     warnings += s;
                 }
             }
             foreach (SearchQueryResult res in search.Result.QueryResults)
             {
                 if (res.HasWarning)
                     warnings += res.Warning;
                 foreach (Match match in res.Matches)
                 {
                     ///取出全部符合條件的Id
                     int strId = Convert.ToInt32(match.DocumentId);
                     if (!idList.Contains(strId))
                     {
                         idList.Add(strId);
                     }
                 }
             }
                 
         }
         catch (SphinxException ex)
         {
             throw new Exception("ProductSearchDao-->GetIdList:warnings: " + warnings + "連接失敗信息:" + ex.Message);
         }
     }
     return idList;
 }
Exemple #2
0
        public IList<SearchQueryResult> searchBible(
            String searchString,
            int translation,
            int bookID,
            int testament)
        {
            using (ConnectionBase connection = new PersistentTcpConnection("127.0.0.1", 9312))
            {
                // Create new search query object and pass query text as argument
                SearchQuery searchQuery = new SearchQuery(searchString);
                // Set match mode to SPH_MATCH_EXTENDED2
                searchQuery.MatchMode = MatchMode.All;
                // Add Sphinx index name to list
                searchQuery.Indexes.Add("test1");
                // Setup attribute
                searchQuery.AttributeFilters.Add("translation", translation, false);
                if (bookID != -1)
                {
                    searchQuery.AttributeFilters.Add("book", bookID, false);
                }

                if (testament != -1)
                {
                    searchQuery.AttributeFilters.Add("testament", testament, false);
                }
                // Set amount of matches will be returned to client
                searchQuery.Limit = 50;

                // Create search command object
                SearchCommand searchCommand = new SearchCommand(connection);
                // Add newly created search query object to query list
                searchCommand.QueryList.Add(searchQuery);
                // Execute command on server and obtain results
                searchCommand.Execute();
                return searchCommand.Result.QueryResults;
            }
        }
Exemple #3
0
        private string DoSearch()
        {
            // set hostname and port defaults
            using (TcpConnection connection = new PersistentTcpConnection(Host, Port))
            {

                SearchCommand search = new SearchCommand(connection);
                SearchQuery query = new SearchQuery(QueryString);
                // Sphinx indexes
                query.Indexes.UnionWith(Indexes);
                // select fields clause
                query.Select = SelectFields;
                // match type
                query.MatchMode = MatchMode;
                // ranking
                query.RankingMode = RankingMode;
                // comment
                query.Comment = Comment;
                // sorting
                query.SortMode = SortMode;
                query.SortBy = SortClause;
                // limits
                query.Limit = query.MaxMatches = MaxMatches;
                // document id filtering
                query.MinDocumentId = MinDocumentId;
                query.MaxDocumentId = MaxDocumentId;
                // grouping
                query.GroupFunc = GroupFunc;
                query.GroupBy = GroupBy;
                query.GroupSort = GroupSortBy;
                query.GroupDistinct = GroupDistinct;

                //query.AttributeFilters.Add(new AttributeFilterRangeDateTime("PublishDate", PublicationStartDate.Value, PublicationEndDate.Value, false));

                // index weights
                foreach (NameValuePair item in _indexWeights)
                {
                    if (!query.IndexWeights.ContainsKey(item.Name))
                        query.IndexWeights.Add(item.Name, item.Value);
                }

                // fields weights
                foreach (NameValuePair item in _fieldWeights)
                {
                    if (!query.FieldWeights.ContainsKey(item.Name)) 
                        query.FieldWeights.Add(item.Name, item.Value);
                }

                // attribute overrides
                foreach (AttributeOverrideMapping item in _attributeOverrides)
                {
                    AttributeOverrideBase attr;
                    AttributeType type = (AttributeType) item.Type;
                    if (!query.AttributeOverrides.Contains(item.Name))
                    {
                        switch (type)
                        {
                            case AttributeType.Integer:
                                Dictionary<long, int> ints = new Dictionary<long, int>();
                                ints.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                attr = new AttributeOverrideInt32(item.Name, ints);
                                break;
                            case AttributeType.Bigint:
                                Dictionary<long, long> longs = new Dictionary<long, long>();
                                longs.Add(item.DocumentId, Convert.ToInt64(item.Value));
                                attr = new AttributeOverrideInt64(item.Name, longs);
                                break;
                            case AttributeType.Boolean:
                                Dictionary<long, bool> bools = new Dictionary<long, bool>();
                                bools.Add(item.DocumentId, Convert.ToBoolean(item.Value));
                                attr = new AttributeOverrideBoolean(item.Name, bools);
                                break;
                            case AttributeType.Float:
                                Dictionary<long, float> floats = new Dictionary<long, float>();
                                floats.Add(item.DocumentId, float.Parse(item.Value.ToString()));
                                attr = new AttributeOverrideFloat(item.Name, floats);
                                break;
                            case AttributeType.Ordinal:
                                Dictionary<long, int> ordinals = new Dictionary<long, int>();
                                ordinals.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                attr = new AttributeOverrideOrdinal(item.Name, ordinals);
                                break;
                            case AttributeType.Timestamp:
                                Dictionary<long, DateTime> timestamps = new Dictionary<long, DateTime>();
                                timestamps.Add(item.DocumentId, Convert.ToDateTime(item.Value));
                                attr = new AttributeOverrideDateTime(item.Name, timestamps);
                                break;
                            default:
                                throw new InvalidOperationException("Unknown attribute type");
                        }
                        query.AttributeOverrides.Add(attr);
                    }
                    else
                    {
                        attr = query.AttributeOverrides[item.Name];
                        if (type != attr.AttributeType) throw new InvalidOperationException("Attribute type mismatch");
                        switch (type)
                        {
                            case AttributeType.Integer:
                                ((AttributeOverrideInt32) attr).Values.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                break;
                            case AttributeType.Bigint:
                                ((AttributeOverrideInt64)attr).Values.Add(item.DocumentId, Convert.ToInt64(item.Value));
                                break;
                            case AttributeType.Boolean:
                                ((AttributeOverrideBoolean)attr).Values.Add(item.DocumentId, Convert.ToBoolean(item.Value));
                                break;
                            case AttributeType.Float:
                                ((AttributeOverrideFloat)attr).Values.Add(item.DocumentId, float.Parse(item.Value.ToString()));
                                break;
                            case AttributeType.Ordinal:
                                ((AttributeOverrideOrdinal)attr).Values.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                break;
                            case AttributeType.Timestamp:
                                ((AttributeOverrideDateTime)attr).Values.Add(item.DocumentId, Convert.ToDateTime(item.Value));
                                break;
                            default:
                                throw new InvalidOperationException("Unknown attribute type");
                        }
                    }
                }

                // add new query
                search.QueryList.Add(query);

                // run the query and get the results
                string output = "";
                try
                {
                    search.Execute();
                }
                catch (SphinxException ex)
                {
                    output = "<h2 style='color: red;'>Error is occured:<h2>" + ex.Message;
                    return output;
                }
                if (search.Result.Status == CommandStatus.Warning)
                {
                    output = "<h2 style='color: olive;'>Warnings: </h2><ul>";
                    foreach (var s in search.Result.Warnings)
                    {
                        output += "<li>" + s + "</li>";
                    }
                    output += "</ul>";
                }
                foreach (SearchQueryResult res in search.Result.QueryResults)
                {
                    output += ParseResult(res);
                }
                return output;
            }
        }
        private IEnumerable<SphinxDocumentAnnounce> GetSphinxSearchResults(string q, string[] indexes = null)
        {
            if (string.IsNullOrEmpty(q))
                return new SphinxDocumentAnnounce[0];

            using (ConnectionBase connection = new PersistentTcpConnection(MeridianMonitor.Default.SphinxHost, MeridianMonitor.Default.SphinxPort))
            {
                q = q.Replace(" -", "¦").Replace("-", " ").Replace("¦", " -").Replace("!", "\\!").Replace("?", "\\?").Replace("@", "\\@");

                if (q.LastIndexOf('-') == (q.Length - 1))
                {
                    q = q.Substring(0, q.LastIndexOf('-') - 1).Trim();
                }

                q = string.Join(" ", q.Split(' ').Select(s => s.Trim()));
                // Create new search query object and pass query text as argument
                SearchQuery searchQuery = new SearchQuery(q);
                // Set match mode to SPH_MATCH_EXTENDED2
                searchQuery.MatchMode = MatchMode.All;

                string[] protos = indexes ?? new string[]
                    {
                        typeof(hotels).Name,
                        //typeof(countries).Name,
                        typeof(deseases).Name,
                        typeof(cure_profiles).Name,
                        typeof(health_factors).Name,
                        //typeof(regions).Name,
                        //typeof(resort_zones).Name,
                        typeof(resorts).Name,
                        typeof(treatment_options).Name,
                        "static_pages",
                        typeof(dictionary).Name
                    };

                var byIndexResults = new Dictionary<string, List<SphinxDocumentAnnounce>>();
                foreach (var protoIndex in protos)
                {
                    searchQuery.Indexes.Add(protoIndex);
                    byIndexResults[protoIndex] = new List<SphinxDocumentAnnounce>();
                }

                searchQuery.Limit = 5000;
                SearchCommand searchCommand = new SearchCommand(connection);
                searchCommand.QueryList.Add(searchQuery);
                searchCommand.Execute();

                var pubResult = new List<SphinxDocumentAnnounce>();
                foreach (SearchQueryResult result in searchCommand.Result.QueryResults)
                {
                    foreach (var match in result.Matches)
                    {
                        var otype = match.AttributesValues["objecttype"].GetValue().ToString().Trim();
                        var entityId = Convert.ToInt64(match.AttributesValues["entityid"].GetValue());
                        var documentId = new DocumentId(entityId);
                        if (match.AttributesValues.Contains("fieldsetid"))
                            documentId = new DocumentId(entityId,
                                Convert.ToInt64(match.AttributesValues["fieldsetid"].GetValue()));

                        if (!Meridian.Default.Exists(otype, entityId))
                            continue;

                        var entity = Meridian.Default.GetAs<ISphinxExportableEntity>(otype, entityId);
                        var document = entity.GetDocumentById(documentId);
                        if (document != null)
                        {
                            var item = new SphinxDocumentAnnounce(document.GetTitle(), document.GetBody(), document.GetUrl());
                            pubResult.Add(item);
                            byIndexResults[otype].Add(item);
                        }
                    }
                }

                var itemsArray = pubResult.ToArray();

                var querySplit = q.Split(' ');
                foreach (var protoIndex in protos)
                {
                    var items = byIndexResults[protoIndex];

                    if (items.Count == 0)
                        continue;

                    BuildExcerptsCommand excerptsCommand = new BuildExcerptsCommand(connection,
                        items.Select(s => s.GetBody()), querySplit, protoIndex);
                    excerptsCommand.Execute();

                    var index = 0;
                    foreach (var result in excerptsCommand.Result.Excerpts)
                    {
                        var item = items[index++];
                        item.SetBody(result);
                    }
                }

                return itemsArray;
            }
        }