首页 > 解决方案 > 通过 .NET Core 控制台应用迭代地将数据推送到 Azure 搜索索引

问题描述

https://docs.microsoft.com/en-us/azure/search/search-get-started-dotnet#2---load-documents

我正在按照此文档以编程方式将文档上传到索引,但是它们在每个文档中都进行了硬编码,如下所示:

IndexDocumentsBatch<Hotel> batch = IndexDocumentsBatch.Create(
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "1",
                HotelName = "Secret Point Motel",
                Description = "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.",
                DescriptionFr = "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.",
                Category = "Boutique",
                Tags = new[] { "pool", "air conditioning", "concierge" },
                ParkingIncluded = false,
                LastRenovationDate = new DateTimeOffset(1970, 1, 18, 0, 0, 0, TimeSpan.Zero),
                Rating = 3.6,
                Address = new Address()
                {
                    StreetAddress = "677 5th Ave",
                    City = "New York",
                    StateProvince = "NY",
                    PostalCode = "10022",
                    Country = "USA"
                }
            }),
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "2",
                HotelName = "Twin Dome Motel",
                Description = "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.",
                DescriptionFr = "L'hôtel est situé dans une place du XIXe siècle, qui a été agrandie et rénovée aux plus hautes normes architecturales pour créer un hôtel moderne, fonctionnel et de première classe dans lequel l'art et les éléments historiques uniques coexistent avec le confort le plus moderne.",
                Category = "Boutique",
                Tags = new[] { "pool", "free wifi", "concierge" },
                ParkingIncluded = false,
                LastRenovationDate = new DateTimeOffset(1979, 2, 18, 0, 0, 0, TimeSpan.Zero),
                Rating = 3.60,
                Address = new Address()
                {
                    StreetAddress = "140 University Town Center Dr",
                    City = "Sarasota",
                    StateProvince = "FL",
                    PostalCode = "34243",
                    Country = "USA"
                }
            }),
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "3",
                HotelName = "Triple Landscape Hotel",
                Description = "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
                DescriptionFr = "L'hôtel est situé dans une place du XIXe siècle, qui a été agrandie et rénovée aux plus hautes normes architecturales pour créer un hôtel moderne, fonctionnel et de première classe dans lequel l'art et les éléments historiques uniques coexistent avec le confort le plus moderne.",
                Category = "Resort and Spa",
                Tags = new[] { "air conditioning", "bar", "continental breakfast" },
                ParkingIncluded = true,
                LastRenovationDate = new DateTimeOffset(2015, 9, 20, 0, 0, 0, TimeSpan.Zero),
                Rating = 4.80,
                Address = new Address()
                {
                    StreetAddress = "3393 Peachtree Rd",
                    City = "Atlanta",
                    StateProvince = "GA",
                    PostalCode = "30326",
                    Country = "USA"
                }
            }),
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "4",
                HotelName = "Sublime Cliff Hotel",
                Description = "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 1800 palace.",
                DescriptionFr = "Le sublime Cliff Hotel est situé au coeur du centre historique de sublime dans un quartier extrêmement animé et vivant, à courte distance de marche des sites et monuments de la ville et est entouré par l'extraordinaire beauté des églises, des bâtiments, des commerces et Monuments. Sublime Cliff fait partie d'un Palace 1800 restauré avec amour.",
                Category = "Boutique",
                Tags = new[] { "concierge", "view", "24-hour front desk service" },
                ParkingIncluded = true,
                LastRenovationDate = new DateTimeOffset(1960, 2, 06, 0, 0, 0, TimeSpan.Zero),
                Rating = 4.60,
                Address = new Address()
                {
                    StreetAddress = "7400 San Pedro Ave",
                    City = "San Antonio",
                    StateProvince = "TX",
                    PostalCode = "78216",
                    Country = "USA"
                }
            })
        );

我怎样才能做同样的事情,但迭代地使用我的对象列表(比如酒店对象列表)?这按原样工作,但我需要上传我的数据,即 800 多个文档,我无法手动输入所有这些数据。

例如这样的事情(我试过这不起作用):

IndexDocumentsBatch<Hotel> batch = IndexDocumentsBatch.Create(
                foreach (var h in hotels)
                    IndexDocumentsAction.Upload(h);

                );     

标签: c#azureazure-cognitive-search

解决方案


解决方案实际上是微不足道的。

只需使用您的 SearchClient 并使用从您的对象列表创建的批处理索引文档。见下文:

# List object of hotels
            var batch = IndexDocumentsBatch.MergeOrUpload(hotels);
# Try to upload
            try
            {
                IndexDocumentsResult result = searchClient.IndexDocuments(batch);
            }
            catch (Exception)
            {
                // If for some reason any documents are dropped during indexing, you can compensate by delaying and
                // retrying. This simple demo just logs the failed document keys and continues.
                Console.WriteLine("Failed to index some of the documents: {0}");
            }

作为参考,如果有人处于类似的位置,我从数据库中提取 JSON 数据并将其反序列化为对象列表 - 在本例中为酒店列表 - 然后只需运行上述代码即可将这些文档推送到索引。


推荐阅读