private async Task <SearchIndex> CreateDemoIndexAsync(SearchIndexClient indexClient)
        {
            FieldBuilder builder = new FieldBuilder();
            var          index   = new SearchIndex(_indexName)
            {
                Fields = builder.Build(typeof(DemoIndex))
            };

            try
            {
                indexClient.GetIndex(index.Name);
                indexClient.DeleteIndex(index.Name);
            }
            catch (RequestFailedException ex) when(ex.Status == 404)
            {
                //if the specified index not exist, 404 will be thrown.
            }

            try
            {
                await indexClient.CreateIndexAsync(index);
            }
            catch (RequestFailedException ex)
            {
                throw new Exception("Failed to create the index", ex);
            }

            return(index);
        }
        public async Task <string> CreateIndexAndIndexerAsync()
        {
            // Create or Update the data source
            SearchIndexerDataSourceConnection dataSource = CreateOrUpdateDataSource(_indexerClient);

            // Create the skills
            OcrSkill                 ocrSkill                 = CreateOcrSkill();
            MergeSkill               mergeSkill               = CreateMergeSkill();
            EntityRecognitionSkill   entityRecognitionSkill   = CreateEntityRecognitionSkill();
            LanguageDetectionSkill   languageDetectionSkill   = CreateLanguageDetectionSkill();
            SplitSkill               splitSkill               = CreateSplitSkill();
            KeyPhraseExtractionSkill keyPhraseExtractionSkill = CreateKeyPhraseExtractionSkill();

            // Create the skillset
            List <SearchIndexerSkill> skills = new List <SearchIndexerSkill>();

            skills.Add(ocrSkill);
            skills.Add(mergeSkill);
            skills.Add(languageDetectionSkill);
            skills.Add(splitSkill);
            skills.Add(entityRecognitionSkill);
            skills.Add(keyPhraseExtractionSkill);

            SearchIndexerSkillset skillset = CreateOrUpdateDemoSkillSet(_indexerClient, skills, _cognitiveServicesKey);

            // Create the index
            SearchIndex demoIndex = await CreateDemoIndexAsync(_indexClient);

            // Create the indexer, map fields, and execute transformations
            SearchIndexer demoIndexer = await CreateDemoIndexerAsync(_indexerClient, dataSource, skillset, demoIndex);

            // Check indexer overall status
            return(await CheckIndexerOverallStatusAsync(_indexerClient, demoIndexer.Name));
        }
Пример #3
0
        public List <Item> Search(List <string> text)
        {
            // perform 3 queries in a single API call:
            //  - 1st query targets index `categories`
            //  - 2nd and 3rd queries target index `products`
            var indexQueries = new List <MultipleQueries>();

            foreach (var item in text)
            {
                indexQueries.Add(new MultipleQueries()
                {
                    IndexName = "Items", Params = new Query(item)
                });
            }

            MultipleQueriesRequest request = new MultipleQueriesRequest
            {
                Requests = indexQueries
            };

            SearchClient client = new SearchClient("BIW6EL1FTD", "8ae9274c008b76fdd8046bd43447044b");
            SearchIndex  index  = client.InitIndex("Items");

            var res = client.MultipleQueries <Item>(request);

            List <Item> results = new List <Item>();

            foreach (var item in res.Results)
            {
                results = results.Union(item.Hits).ToList();
            }
            ;

            return(results.Distinct(new ItemComparer()).ToList());
        }
Пример #4
0
        public void SetUpFixture()
        {
            base.CreateClient();

            var getIndexResult = client.GetSearchIndex("scores");

            if (!getIndexResult.IsSuccess)
            {
                var searchIndex = new SearchIndex("scores", "_yz_default");
                CheckResult(client.PutSearchIndex(searchIndex));
            }

            getIndexResult = client.GetSearchIndex("hobbies");
            if (!getIndexResult.IsSuccess)
            {
                var searchIndex = new SearchIndex("hobbies", "_yz_default");
                CheckResult(client.PutSearchIndex(searchIndex));
            }

            getIndexResult = client.GetSearchIndex("customers");
            if (!getIndexResult.IsSuccess)
            {
                var searchIndex = new SearchIndex("customers", "_yz_default");
                CheckResult(client.PutSearchIndex(searchIndex));
            }
        }
Пример #5
0
        public async Task AddEntity <T>(T entity, string indexName) where T : class
        {
            SearchIndex index = _client.InitIndex(indexName);
            await index.SaveObjectAsync(entity);

            ListProducts();
        }
Пример #6
0
        public List <Item> RandomItems()
        {
            SearchClient         client        = new SearchClient("BIW6EL1FTD", "a5af55b1831c11747c108cc179f2d790");
            SearchIndex          index         = client.InitIndex("Items");
            IndexIterator <Item> indexIterator = index.Browse <Item>(new BrowseIndexQuery {
            });

            var hits = new List <Item>();

            int max = 0;

            foreach (var hit in indexIterator)
            {
                if (hit.ImageURL != "null")
                {
                    hits.Add(hit);
                }

                if (max > 100)
                {
                    break;
                }
                else
                {
                    max++;
                }
            }
            Random rnd = new Random();

            return(hits.Where(t => t.ImageURL.ToLower() != "null").OrderBy(x => rnd.Next()).Take(20).ToList());
        }
Пример #7
0
        void sender_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
        {
            if (!IsSearchable(sender, e.Row))
            {
                return;
            }

            Guid?noteID = (Guid?)sender.GetValue(e.Row, _FieldOrdinal);

            Note note = PXSelect <Note, Where <Note.noteID, Equal <Required <Note.noteID> > > > .Select(sender.Graph, noteID);

            SearchIndex si = BuildSearchIndex(sender, e.Row, null, note != null ? note.NoteText : null);

            if (e.TranStatus == PXTranStatus.Completed)
            {
                if (noteID == null)
                {
                    throw new PXException("SearchIndex cannot be saved. NoteID is required for an entity to be searchable but it has not been supplied.");
                }

                if (e.Operation == PXDBOperation.Delete)
                {
                    PXDatabase.Delete(typeof(SearchIndex),
                                      new PXDataFieldRestrict(typeof(SearchIndex.noteID).Name, PXDbType.UniqueIdentifier, si.NoteID));
                }
                else
                {
                    if (!Update(si))
                    {
                        Insert(si);
                    }
                }
            }
        }
Пример #8
0
        public void Init()
        {
            var indexName = TestHelper.GetTestIndexName("search");

            _index     = BaseTest.SearchClient.InitIndex(indexName);
            _employees = InitEmployees();
        }
Пример #9
0
        public void SearchTest()
        {
            var config = new SearchIndexConfig();

            using (var searchIndex = new SearchIndex(CreateDefaultSearchIndex, config))
            {
                var result = searchIndex.Search("file content");
                Assert.AreEqual(2, result.Total);

                result = searchIndex.Search("*ile");
                Assert.AreEqual(2, result.Total);

                result = searchIndex.Search("ile");
                Assert.AreEqual(2, result.Total);

                result = searchIndex.Search("tte");
                Assert.AreEqual(2, result.Total);

                result = searchIndex.Search("reft");
                Assert.AreEqual(1, result.Total);

                result = searchIndex.Search("stile");
                Assert.AreEqual(1, result.Total);
            }
        }
        public async Task VerifyOrCreateFtsIndexes(string indexName, string bucketName)
        {
            try
            {
                var existingIndex = await _fixture.Cluster.SearchIndexes.GetIndexAsync(indexName);
                if (existingIndex.Type == "fulltext-index")
                {
                    _outputHelper.WriteLine($"'{indexName}' already exists.");
                    return;
                }
            }
            catch (Exception e)
            {
                _outputHelper.WriteLine($"Failure looking up '{indexName}': {e.ToString()}");
            }

            _outputHelper.WriteLine($"Attempting to create fulltext index '{indexName}'");
            var searchIndex = new SearchIndex()
            {
                Name = "idx-travel",
                SourceName = bucketName,
                SourceType = "couchbase",
                Type = "fulltext-index"
            };

            try
            {
                await _fixture.Cluster.SearchIndexes.UpsertIndexAsync(searchIndex, UpsertSearchIndexOptions.Default);
            }
            catch (HttpRequestException e)
            {
                _outputHelper.WriteLine(e.ToString());
                throw;
            }
        }
Пример #11
0
        static SearchIndex CreateIndex(string indexName)
        {
            SearchIndex index = new SearchIndex(indexName)
            {
                Fields =
                {
                    new SimpleField("id",            SearchFieldDataType.String)
                    {
                        IsKey = true,                IsFilterable= true, IsSortable = true
                    },
                    new SearchableField("url")
                    {
                        IsFilterable = true,         IsSortable = true
                    },
                    new SearchableField("file_name")
                    {
                        IsFilterable = true,         IsSortable = true
                    },
                    new SearchableField("content")
                    {
                        IsFilterable = true,         IsSortable = true
                    },
                    new SimpleField("size",          SearchFieldDataType.Int64)
                    {
                        IsFilterable = true,         IsSortable = true
                    },
                    new SimpleField("last_modified", SearchFieldDataType.DateTimeOffset)
                    {
                        IsFilterable = true,         IsSortable = true
                    },
                }
            };

            return(index);
        }
Пример #12
0
 private static void VerifyIndex(SearchIndex definition, SearchIndex index)
 {
     Assert.NotNull(index);
     Assert.Equal(definition.Name, index.Name);
     Assert.Equal(definition.Type, index.Type);
     Assert.NotEmpty(index.Uuid);
 }
Пример #13
0
        public ActionResult AutoComplete(string searchText)
        {
            var q           = new List <JsonItem>();
            var contextItem = PageContext.Current.Item;

            using (IProviderSearchContext searchContext = SearchIndex.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
            {
                var contextItemShortId = contextItem.ID.ToShortID().ToString().ToLowerInvariant();
                var queryable          = searchContext.GetQueryable <CustomSearchResultItem>();
                queryable = queryable.Where(i =>
                                            i.GuidPath.Equals(contextItemShortId) &&
                                            (
                                                i.Name.StartsWith(searchText) ||
                                                i.Content.Contains(searchText)
                                            )).Take(100);
                queryable.ToList().ForEach(r =>
                {
                    var i = r.GetItem();
                    q.Add(new JsonItem()
                    {
                        ID           = i.ID.Guid,
                        Name         = i.Name,
                        DisplayName  = i.DisplayName,
                        Path         = i.Paths.FullPath,
                        RelativeLink = Sitecore.Links.LinkManager.GetItemUrl(i),
                        PageTitle    = !string.IsNullOrEmpty(i["PageTitle"]) ? i["PageTitle"] : i.DisplayName,
                        ButtonTitle  = !string.IsNullOrEmpty(i["ButtonTitle"]) ? i["ButtonTitle"] : i.DisplayName
                    });
                });
            }
            return(Json(q, JsonRequestBehavior.AllowGet));
        }
        public void SettingFieldsOverwrites()
        {
            SearchIndex sut = new SearchIndex("test", new SearchField[]
            {
                new SimpleField("a", SearchFieldDataType.String)
                {
                    IsKey = true
                },
                new SearchableField("b")
                {
                    IsSortable = true
                },
            });

            SearchField[] fields = new SearchField[]
            {
                new SimpleField("id", SearchFieldDataType.String)
                {
                    IsKey = true
                },
                new SearchableField("name")
                {
                    IsSortable = true
                },
            };

            sut.Fields = fields;

            Assert.That(sut.Fields, Is.EqualTo(fields).Using(SearchFieldComparer.SharedFieldsCollection));
        }
Пример #15
0
        public async Task CreateIndex()
        {
            await using SearchResources resources = SearchResources.CreateWithNoIndexes(this);
            Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", resources.Endpoint.ToString());
            Environment.SetEnvironmentVariable("SEARCH_API_KEY", resources.PrimaryApiKey);

            #region Snippet:Azure_Search_Tests_Samples_Readme_CreateIndex
            Uri    endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
            string key      = Environment.GetEnvironmentVariable("SEARCH_API_KEY");

            // Create a service client
            AzureKeyCredential credential = new AzureKeyCredential(key);
            SearchIndexClient  client     = new SearchIndexClient(endpoint, credential);
            /*@@*/ client = resources.GetIndexClient();

            // Create the index using FieldBuilder.
            #region Snippet:Azure_Search_Tests_Samples_Readme_CreateIndex_New_SearchIndex
            //@@SearchIndex index = new SearchIndex("hotels")
            /*@@*/ SearchIndex index = new SearchIndex(Recording.Random.GetName())
            {
                Fields     = new FieldBuilder().Build(typeof(Hotel)),
                Suggesters =
                {
                    // Suggest query terms from the hotelName field.
                    new SearchSuggester("sg", "hotelName")
                }
            };
            #endregion Snippet:Azure_Search_Tests_Samples_Readme_CreateIndex_New_SearchIndex

            client.CreateIndex(index);
            #endregion Snippet:Azure_Search_Tests_Samples_Readme_CreateIndex

            resources.IndexName = index.Name;
        }
        public async Task TestApiKey()
        {
            var addOne = await _index1.SaveObjectAsync(new SecuredApiKeyStub { ObjectID = "one" });

            var addTwo = await _index2.SaveObjectAsync(new SecuredApiKeyStub { ObjectID = "one" });

            addOne.Wait();
            addTwo.Wait();

            SecuredApiKeyRestriction restriction = new SecuredApiKeyRestriction
            {
                ValidUntil      = DateTime.UtcNow.AddMinutes(10).ToUnixTimeSeconds(),
                RestrictIndices = new List <string> {
                    _index1Name
                }
            };

            string key = BaseTest.SearchClient.GenerateSecuredApiKeys(TestHelper.SearchKey1, restriction);

            SearchClient clientWithRestriciton    = new SearchClient(TestHelper.ApplicationId1, key);
            SearchIndex  index1WithoutRestriction = clientWithRestriciton.InitIndex(_index1Name);
            SearchIndex  index2WithRestriction    = clientWithRestriciton.InitIndex(_index2Name);

            await index1WithoutRestriction.SearchAsync <SecuredApiKeyStub>(new Query());

            AlgoliaApiException ex = Assert.ThrowsAsync <AlgoliaApiException>(() =>
                                                                              index2WithRestriction.SearchAsync <SecuredApiKeyStub>(new Query()));

            Assert.That(ex.Message.Contains("Index not allowed with this API key"));
            Assert.That(ex.HttpErrorCode == 403);
        }
 public void Init()
 {
     _index1Name = TestHelper.GetTestIndexName("secured_api_keys");
     _index2Name = TestHelper.GetTestIndexName("secured_api_keys_dev");
     _index1     = BaseTest.SearchClient.InitIndex(_index1Name);
     _index2     = BaseTest.SearchClient.InitIndex(_index2Name);
 }
        public void Init()
        {
            _indexName = TestHelper.GetTestIndexName("synonyms");
            _index     = BaseTest.SearchClient.InitIndex(_indexName);

            _objectsToSave = new List <SynonymTestObject>
            {
                new SynonymTestObject {
                    Console = "Sony PlayStation <PLAYSTATIONVERSION>"
                },
                new SynonymTestObject {
                    Console = "Nintendo Switch"
                },
                new SynonymTestObject {
                    Console = "Nintendo Wii U"
                },
                new SynonymTestObject {
                    Console = "Nintendo Game Boy Advance"
                },
                new SynonymTestObject {
                    Console = "Microsoft Xbox"
                },
                new SynonymTestObject {
                    Console = "Microsoft Xbox 360"
                },
                new SynonymTestObject {
                    Console = "Microsoft Xbox One"
                }
            };
        }
Пример #19
0
        public ActionResult SearchStoreByLocation(FormCollection form)
        {
            SearchIndex search = new SearchIndex();


            if (form["storeLocation"] != null)
            {
                search.Name            = form["storeLocation"];
                ViewBag.Name           = search.Name;
                TempData["searchName"] = ViewBag.Name;
                ViewBag.searchName     = searchRepository.searchLocation(search);
                ViewBag.quantity       = searchRepository.calculateLocationQuantity(search);

                if (ViewBag.searchName == null)
                {
                    //Create new log

                    searchRepository.log4(search);
                    return(View("ResultNotExists"));
                }
                else
                {
                    //Create new log

                    searchRepository.log3(search);

                    return(View("ResultStore", searchRepository.findSearchLocation(search)));
                }
            }
            return(View());
        }
Пример #20
0
        /// <summary>
        ///   Starts the searching.
        /// </summary>
        private void StartSearching()
        {
            UseWaitCursor = true;
            try
            {
                if (!string.IsNullOrEmpty(searchText.Text) && !string.IsNullOrEmpty(selectedFolder))
                {
                    string[] pdfFiles = Directory.GetFiles(selectedFolder, "*.pdf", SearchOption.TopDirectoryOnly);
                    foreach (string pdfFile in pdfFiles)
                    {
                        currentSearchFileName = pdfFile;
                        using (FileStream stream = new FileStream(pdfFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            SearchIndex searchIndex = new SearchIndex(stream);

                            // search text in PDF document and render pages containg results
                            searchIndex.Search(OnSearchItem, searchText.Text);
                        }

                        if (CancelSearching)
                        {
                            UseWaitCursor = false;
                            break;
                        }
                    }
                }
            }
            finally
            {
                //Nothing was found
                currentSearchFileName = string.Empty;
                UseWaitCursor         = false;
            }
        }
Пример #21
0
        public ActionResult SearchStoreByZipCode(FormCollection form)
        {
            SearchIndex search = new SearchIndex();


            if (form["storeZipcode"] != null)
            {
                search.Name = form["storeZipcode"];
                int?test = Convert.ToInt32(search.Name);
                ViewBag.Name           = search.Name;
                TempData["searchName"] = ViewBag.Name;
                ViewBag.searchName     = searchRepository.searchZipCode(test);
                ViewBag.quantity       = searchRepository.calculateZipCodeQuantity(test);

                if (ViewBag.searchName == null)
                {
                    //Create new log
                    searchRepository.log4(search);
                    return(View("ResultNotExists"));
                }
                else
                {
                    //Create new log
                    searchRepository.log3(search);
                    return(View("ResultStore", searchRepository.storeListByZipCode(test)));
                }
            }

            return(View());
        }
        public List <ClubAlgolia> Algolia()
        {
            // Add the data to Algolia
            SearchClient       client = new SearchClient("ZJ5YQA6729", "ef857c06f1ebf56ed75841fc6c2df18b");
            SearchIndex        index  = client.InitIndex("ClubFoot");
            List <ClubAlgolia> clubs  = new List <ClubAlgolia>();

            foreach (Club club in _context.Clubs.ToList())
            {
                var clubNew = new ClubAlgolia()
                {
                    ObjectID    = club.IdClub.ToString(),
                    Name        = club.Name,
                    Address     = club.Address,
                    Phone       = club.Phone,
                    Email       = club.Email,
                    OpeningTime = club.OpeningTime,
                    ClosingTime = club.ClosingTime
                };
                clubs.Add(clubNew);
            }
            index.ClearObjects();
            // Fetch from DB or a Json file
            index.SaveObjects(clubs);
            return(clubs);
        }
        private static SearchIndex CreateDemoIndex(SearchIndexClient indexClient)
        {
            FieldBuilder builder = new FieldBuilder();
            var          index   = new SearchIndex("demoindex")
            {
                Fields = builder.Build(typeof(DemoIndex))
            };

            try
            {
                indexClient.GetIndex(index.Name);
                indexClient.DeleteIndex(index.Name);
            }
            catch (RequestFailedException ex) when(ex.Status == 404)
            {
                //if the specified index not exist, 404 will be thrown.
            }

            try
            {
                indexClient.CreateIndex(index);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine("Failed to create the index\n Exception message: {0}\n", ex.Message);
                ExitProgram("Cannot continue without an index");
            }

            return(index);
        }
 private static SearchIndex AddSynonymMapsToFields(SearchIndex index)
 {
     //remove SynonymMaps attribute in class hotel, need Add maps manually.
     index.Fields.First(f => f.Name == "Category").SynonymMapNames.Add("desc-synonymmap");
     index.Fields.First(f => f.Name == "Tags").SynonymMapNames.Add("desc-synonymmap");
     return(index);
 }
        // This sample shows how to create a synonym-map and an index that are encrypted with customer-managed key in Azure Key Vault
        static void Main(string[] args)
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();

            SearchIndexClient indexClient = CreateSearchIndexClient(configuration);

            Console.WriteLine("Cleaning up resources...\n");
            CleanupResources(indexClient);

            Console.WriteLine("Creating synonym-map encrypted with customer managed key...\n");
            CreateSynonymsEncryptedUsingCustomerManagedKey(indexClient, configuration);

            Console.WriteLine("Creating index encrypted with customer managed key...\n");
            CreateHotelsIndexEncryptedUsingCustomerManagedKey(indexClient, configuration);

            SearchIndex index = indexClient.GetIndex("hotels");

            index = AddSynonymMapsToFields(index);
            indexClient.CreateOrUpdateIndex(index);

            SearchClient searchClient = indexClient.GetSearchClient("hotels");

            Console.WriteLine("Uploading documents...\n");
            UploadDocuments(searchClient);

            SearchClient searchClientForQueries = CreateSearchClient(configuration);

            RunQueries(searchClientForQueries);

            Console.WriteLine("Complete.  Press any key to end application...\n");
            Console.ReadKey();
        }
Пример #26
0
        public async Task <Response <SearchIndex> > CreateAsync(SearchIndex index, CancellationToken cancellationToken = default)
        {
            if (index == null)
            {
                throw new ArgumentNullException(nameof(index));
            }

            using var message = CreateCreateRequest(index);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 201:
            {
                SearchIndex value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                if (document.RootElement.ValueKind == JsonValueKind.Null)
                {
                    value = null;
                }
                else
                {
                    value = SearchIndex.DeserializeSearchIndex(document.RootElement);
                }
                return(Response.FromValue(value, message.Response));
            }
        public void Init()
        {
            SetUp();

            var index = new SearchIndex(Index);

            Client.PutSearchIndex(index);

            Func <RiakResult <RiakBucketProperties>, bool> indexIsSet =
                result => result.IsSuccess &&
                result.Value != null &&
                !string.IsNullOrEmpty(result.Value.SearchIndex);

            Func <RiakResult <RiakBucketProperties> > setBucketProperties =
                () =>
            {
                RiakBucketProperties props = Client.GetBucketProperties(BucketType, Bucket).Value;
                props.SetSearchIndex(Index);
                Client.SetBucketProperties(BucketType, Bucket, props);
                return(Client.GetBucketProperties(BucketType, Bucket));
            };

            setBucketProperties.WaitUntil(indexIsSet);
            System.Threading.Thread.Sleep(5000); // Wait for Yoko to start up
            PrepSearch();
        }
Пример #28
0
 public void Init()
 {
     _index1Name = TestHelper.GetTestIndexName("ab_testing");
     _index2Name = TestHelper.GetTestIndexName("ab_testing_dev");
     _index1     = BaseTest.SearchClient.InitIndex(_index1Name);
     _index2     = BaseTest.SearchClient.InitIndex(_index2Name);
 }
Пример #29
0
        public ActionResult Index(SearchAdminViewModel svm)
        {
            var messages = new List<MsgViewModel>();

            if (svm.Action == "Requests")
            {
                using (var searchIndex = new SearchIndex<Request, RequestIndexDefinition>())
                {
                    searchIndex.ClearLuceneIndex();
                    searchIndex.AddOrUpdateAll(GetAllRequests());
                    messages.Add(MsgViewModel.SuccessMsg("Index has been rebuilt."));
                }
            }
            /* else if (svm.Action == "Autocomplete")
            {
                using (FSDirectory d = FSDirectory.Open(new DirectoryInfo(SearchIndex<Request, RequestIndexDefinition>.DirPath)))
                {
                    SearchAutoComplete sac = new SearchAutoComplete(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/SearchAutocompleteIndex");
                    sac.BuildAutoCompleteIndex(d, "Keywords");
                }
                messages.Add(MsgViewModel.SuccessMsg("Rebuilt autocomplete index."));
            } */

            ViewBag.Alerts = messages;

            ViewBag.SearchAdminActive = true;
            return View(svm);
        }
Пример #30
0
        static async Task Main(string[] args)
        {
            InitKeys();

            // Init the client
            SearchClient client = new SearchClient(_appKey, _apiKey);

            // Init index
            SearchIndex index = client.InitIndex("AlgoliaDotnetConsole");

            // Push data from Json
            using (StreamReader re = File.OpenText("AlgoliaConsole/Datas/Actors.json"))
                using (JsonTextReader reader = new JsonTextReader(re))
                {
                    JArray batch = JArray.Load(reader);
                    var    ret   = await index.SaveObjectsAsync(batch);

                    ret.Wait();
                }

            // Get data
            var actor = await index.GetObjectAsync <Actor>("551486310");

            Console.WriteLine(actor.ToString());

            // Search
            var search = await index.SearchAsync <Actor>(new Query("monica"));

            Console.WriteLine(search.Hits.ElementAt(0).ToString());
            Environment.Exit(0);
        }
Пример #31
0
        /// <inheritdoc />
        public async Task CreateIndexIfMissingAsync <TEntity>(CancellationToken cancellation)
        {
            var info  = GetEntityInfo <TEntity>();
            var index = await GetIndexAsync(info, cancellation);

            if (index == null)
            {
                var definition = new SearchIndex(info.IndexName)
                {
                    Fields = new FieldBuilder().Build(typeof(TEntity)),
                };

                var analyzers = new List <LexicalAnalyzer>();
                analyzers.AddRange(
                    typeof(TEntity)
                    .GetCustomAttributes <PatternAnalyzerAttribute>()
                    .Select(
                        a => new PatternAnalyzer(a.Name)
                {
                    LowerCaseTerms = a.LoweCaseTerms,
                    Pattern        = a.Pattern,
                }));

                //TODO find the way to add analizers.
                await client.CreateIndexAsync(definition, cancellation);
            }
        }
Пример #32
0
 protected override IJsonToken LibraryResponse(Library library)
 {
     JsonArray array = new JsonArray();
     SearchIndex index = new SearchIndex(library.GetSongs());
     foreach (KeyValuePair<string, List<Song>> kvp in index) {
         array.Add(GetJson(kvp.Key, kvp.Value));
     }
     return array;
 }
Пример #33
0
 public static SearchIndex CreateSearchIndex(int id, string title)
 {
     SearchIndex searchIndex = new SearchIndex();
     searchIndex.ID = id;
     searchIndex.Title = title;
     return searchIndex;
 }
Пример #34
0
        private ItemSearchRequest RequestBuilder(SearchIndex index, string keywords, int page, IEnumerable<ResponseGroup> responseGroups,
            Merchants merchant, int? maximumPrice, int? minimumPrice, int? percentageOff)
        {
            var request = new ItemSearchRequest
            {
                SearchIndex = index.ToString(),
                Keywords = keywords,
                MaximumPrice = maximumPrice != null ? maximumPrice.ToString() : null,
                MinimumPrice = minimumPrice != null ? minimumPrice.ToString() : null,
                MerchantId = merchant.ToString(),
                MinPercentageOff = percentageOff != null ? percentageOff.ToString() : null,
                ItemPage = page.ToString(CultureInfo.InvariantCulture),
                ResponseGroup = new[] { String.Join(",", responseGroups.Select(i => i.ToString()).ToArray()), }
            };

            return request;
        }
Пример #35
0
        public ItemSearchResponse ItemSearch(SearchIndex index, string keywords, int page, List<ResponseGroup> responseGroups,
            Merchants merchant, int? maxPrice, int? minPrice, int? minPercentageOff)
        {
            var request = RequestBuilder(index, keywords, page, responseGroups, merchant, maxPrice, minPrice, minPercentageOff);
            var itemSearch = SearchRequest(request);

            var response = client.ItemSearch(itemSearch);

            return response;
        }
Пример #36
0
 public ItemSearchResponse ItemSearch(SearchIndex index, string keywords, int page, List<ResponseGroup> responseGroups,
     Merchants merchant, int maxPrice, int minPrice)
 {
     return ItemSearch(index, keywords, page, responseGroups, merchant, maxPrice, minPrice, null);
 }
Пример #37
0
 public ItemSearchResponse ItemSearch(SearchIndex index, string keywords, int page)
 {
     var list = new List<ResponseGroup> { ResponseGroup.ItemAttributes, ResponseGroup.OfferFull };
     return ItemSearch(index, keywords, page, list, Merchant, null, null, null);
 }
Пример #38
0
 public void AddToSearchIndexes(SearchIndex searchIndex)
 {
     base.AddObject("SearchIndexes", searchIndex);
 }
        private void pdfViewer1_SearchRequested(object sender, Apitron.PDF.Controls.SearchRequestedEventArgs e)
        {
            if (!string.IsNullOrEmpty(loadedFilePath))
            {
                SearchIndex searchIndex;

                // so we have created the index already
                if (searchDictionary.TryGetValue(loadedFilePath, out searchIndex))
                {
                    e.SearchIndex = searchIndex;
                }
                else
                {
                    searchIndex = new SearchIndex(File.OpenRead(loadedFilePath));
                    searchDictionary.Add(loadedFilePath, searchIndex);

                    e.SearchIndex = searchIndex;
                }
            }

        }
Пример #40
0
 public ItemSearchResponse ItemSearch(SearchIndex index, string keywords, int page, List<ResponseGroup> responseGroups)
 {
     return ItemSearch(index, keywords, page, responseGroups, Merchant, null, null, null);
 }