ElasticsearchCRUD使用(四)【使用EF从SQLServer到Elasticsearch的数据传输】

AdventureWorks2012用作数据库,可以在这里下载。 您需要在代码工作之前安装数据库。

应用程序

创建一个新的控制台应用程序,并从NuGet下载ElasticsearchCRUD和Entity Framework。
这里写图片描述

从AdventureWorks数据库创建代码第一个数据库。

向项目添加一个新项,选择ADO.NET实体数据模型:
这里写图片描述
现在从数据库选项首先选择代码。 数据库已经存在。
这里写图片描述
从Person架构添加所有表。 Address表和Person表将用作文档根。
这里写图片描述

创建的Address类需要更改。 必须删除DbGeography SpatialLocation,因为这不是支持的类型。 在ElasticsearchCRUD V1.0.8或更高版本中,可以使用JsonIgnore属性忽略这一点。

namespace DataTransferSQLToEl.SQLDomainModel
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Person.Address")]
    public partial class Address
    {
        public int AddressID { get; set; }

        [Required]
        [StringLength(60)]
        public string AddressLine1 { get; set; }

        [StringLength(60)]
        public string AddressLine2 { get; set; }

        [Required]
        [StringLength(30)]
        public string City { get; set; }

        public int StateProvinceID { get; set; }

        [Required]
        [StringLength(15)]
        public string PostalCode { get; set; }

        // This type is not supported yet...
        //public DbGeography SpatialLocation { get; set; }

        public Guid rowguid { get; set; }

        public DateTime ModifiedDate { get; set; }

        public virtual StateProvince StateProvince { get; set; }
    }
}

选择实体并将文档添加到Elasticsearch。 Address 传输实现如下:

public void SaveToElasticsearchAddress()
{
    IElasticsearchMappingResolver elasticsearchMappingResolver = new ElasticsearchMappingResolver();
    using (var elasticsearchContext = new ElasticsearchContext("http://localhost:9200/", elasticsearchMappingResolver))
    {
        //elasticsearchContext.TraceProvider = new ConsoleTraceProvider();
        using (var modelPerson = new ModelPerson())
        {
            int pointer = 0;
            const int interval = 100;
            int length = modelPerson.CountryRegion.Count();

            while (pointer < length)
            {
                stopwatch.Start();
                var collection = modelPerson.Address.OrderBy(t => t.AddressID).Skip(pointer).Take(interval).ToList<Address>();
                stopwatch.Stop();
                Console.WriteLine("Time taken for select {0} AddressID: {1}", interval, stopwatch.Elapsed);
                stopwatch.Reset();

                foreach (var item in collection)
                {
                    elasticsearchContext.AddUpdateDocument(item, item.AddressID);
                    string t = "yes";
                }

                stopwatch.Start();
                elasticsearchContext.SaveChanges();
                stopwatch.Stop();
                Console.WriteLine("Time taken to insert {0} AddressID documents: {1}", interval, stopwatch.Elapsed);
                stopwatch.Reset();
                pointer = pointer + interval;
                Console.WriteLine("Transferred: {0} items", pointer);
            }
        }
    }
}

一次选择了一百个实体,并将其添加到ElasticsearchCRUD上下文中。 这只是将对象添加到内存集合中。 调用SaveChanges方法时,将每个实体序列化为JSON对象。 当所有项目都被序列化时,HttpClient实例将HTTP批量POST请求中的所有对象发送到Elasticsearch。 直到所有项都被传输为止。 ElasticsearchCRUD将所有子元素序列化为1-N。 对已经转换的父对象的任何引用都将被忽略并保存为空属性。

创建的Elasticsearch 映射如下(对于Person和Address文档):

{
    "addresss": {
        "mappings": {
            "address": {
                "properties": {
                    "addressid": { "type": "long" },
                    "addressline1": { "type": "string" },
                    "addressline2": { "type": "string" },
                    "city": { "type": "string" },
                    "modifieddate": { "type": "date", "format": "dateOptionalTime" },
                    "postalcode": { "type": "string" },
                    "rowguid": { "type": "string" },
                    "stateprovince": { "properties": { "countryregion": { "properties": { "countryregioncode": { "type": "string" }, "modifieddate": { "type": "date", "format": "dateOptionalTime" }, "name": { "type": "string" } } }, "countryregioncode": { "type": "string" }, "isonlystateprovinceflag": { "type": "boolean" }, "modifieddate": { "type": "date", "format": "dateOptionalTime" }, "name": { "type": "string" }, "rowguid": { "type": "string" }, "stateprovincecode": { "type": "string" }, "stateprovinceid": { "type": "long" }, "territoryid": { "type": "long" } } },
                    "stateprovinceid": { "type": "long" } }
            }
        }
    },
    "persons": {
        "mappings": {
            "person": {
                "properties": {
                    "additionalcontactinfo": { "type": "string" },
                    "businessentityid": { "type": "long" },
                    "demographics": { "type": "string" },
                    "emailaddress": { "properties": { "businessentityid": { "type": "long" }, "emailaddress1": { "type": "string" }, "emailaddressid": { "type": "long" }, "modifieddate": { "type": "date", "format": "dateOptionalTime" }, "rowguid": { "type": "string" } } },
                    "emailpromotion": { "type": "long" },
                    "firstname": { "type": "string" },
                    "lastname": { "type": "string" },
                    "middlename": { "type": "string" },
                    "modifieddate": { "type": "date", "format": "dateOptionalTime" },
                    "namestyle": { "type": "boolean" },
                    "personphone": { "properties": { "businessentityid": { "type": "long" }, "modifieddate": { "type": "date", "format": "dateOptionalTime" }, "phonenumber": { "type": "string" }, "phonenumbertype": { "properties": { "modifieddate": { "type": "date", "format": "dateOptionalTime" }, "name": { "type": "string" }, "phonenumbertypeid": { "type": "long" } } }, "phonenumbertypeid": { "type": "long" } } },
                    "persontype": { "type": "string" },
                    "rowguid": { "type": "string" },
                    "suffix": { "type": "string" },
                    "title": { "type": "string" } }
            }
        }
    }

}

可以使用ElasticsearchCRUD如下读取保存的对象。

ublic Address GetAddressFromElasticsearch(int id)
{
    Address address;
    IElasticsearchMappingResolver elasticsearchMappingResolver = new ElasticsearchMappingResolver();
    using (var elasticsearchContext = new ElasticsearchContext("http://localhost:9200/", elasticsearchMappingResolver))
    {
        address = elasticsearchContext.GetDocument<Address>(id);
    }

    return address;
}

然后可以在控制台应用程序中使用。 完成后,具有嵌套子对象的所有对象将作为文档保存在Elasticsearch中。

using System;

namespace DataTransferSQLToEl
{
    class Program
    {
        static void Main(string[] args)
        {
            var repo = new Repo();
            repo.SaveToElasticsearchPerson();
            repo.SaveToElasticsearchAddress();

            var personX = repo.GetPersonFromElasticsearch(345);
            var addressX = repo.GetAddressFromElasticsearch(22);
            Console.WriteLine(addressX);
            Console.WriteLine(personX);
        }
    }
}

如果您只希望保存父实体,并且不包含子实体(Elasticsearch中的NESTED对象),则可以在ElasticsearchCRUD上下文构造函数中设置此选项:

bool saveChildEntitiesAsNestedObjects = false;

using (var elasticSearchContext = 
              new ElasticsearchContext(
                 "http://localhost:9200/", 
                  elasticsearchMappingResolver, 
                  saveChildEntitiesAsNestedObjects 
              )
      )
{
  // Do you coding here...
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Logstash是一个开源的数据收集引擎,可以从各种源(例如SQL Server)收集数据并将其转发到目标存储(例如Elasticsearch)。 首先,您需要在Logstash的配置文件中定义输入和输出插件。对于SQL Server,您可以使用`jdbc`插件来连接数据库并执行查询,然后使用`elasticsearch`插件将结果发送到Elasticsearch。 在配置文件中,您需要提供SQL Server数据库的连接详细信息,例如主机名、端口、数据库名称、用户和密码。您还需要指定要执行的查询语句和将数据发送到Elasticsearch的目标索引。 以下是一个示例配置文件的概述: ``` input { jdbc { jdbc_driver_library => "path_to_sqlserver_jdbc_driver" jdbc_driver_class => "com.microsoft.sqlserver.jdbc.SQLServerDriver" jdbc_connection_string => "jdbc:sqlserver://<host>:<port>;databaseName=<database>" jdbc_user => "<username>" jdbc_password => "<password>" schedule => "* * * * *" statement => "SELECT * FROM <table>" } } output { elasticsearch { hosts => ["localhost:9200"] index => "my_index" } } ``` 在这个示例中,Logstash将每分钟执行一次查询,并将结果发送到名为`my_index`的Elasticsearch索引中。 通过运行Logstash并指定配置文件,您可以开始将数据SQL Server导入到Elasticsearch。例如,使用以下命令运行Logstash: ``` bin/logstash -f path_to_config_file.conf ``` Logstash将会自动连接到SQL Server数据库,执行查询,并将结果发送到Elasticsearch。 总结起来,使用Logstash的`jdbc`和`elasticsearch`插件,可以轻松实现从SQL ServerElasticsearch数据传输。只需定义合适的配置文件,并在Logstash中运行它即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值