首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加速Django数据库函数用于缺失值的地理插值

加速Django数据库函数用于缺失值的地理插值
EN

Stack Overflow用户
提问于 2018-03-30 08:02:54
回答 1查看 193关注 0票数 1

我有一个大型的商业地产地址数据库(大约500万行),其中200,000所缺少的楼层面积。这些房产是按行业分类的,我知道每个行业的租金。

我插值缺失的楼面面积的方法是,在楼面面积未知的物业的指定半径内,过滤类似分类的物业,然后根据附近物业成本/平方米的中位数计算楼面面积。

最初,我使用熊猫来处理这个问题,但是随着数据集越来越大(甚至使用group_by),这就成了问题。它经常超过可用内存,并停止。当它工作时,大约需要3个小时才能完成。

我正在测试是否可以在数据库中完成相同的任务。我为径向填充编写的函数如下:

代码语言:javascript
复制
def _radial_fill(self):
    # Initial query selecting all latest locations, and excluding null rental valuations
    q = Location.objects.order_by("locode","-update_cycle") \
                        .distinct("locode")
    # Chained Q objects to use in filter
    f = Q(rental_valuation__isnull=False) & \
        Q(use_category__grouped_by__isnull=False) & \
        Q(pc__isnull=False)
    # All property categories at subgroup level
    for c in LocationCategory.objects.filter(use_category="SGP").all():
        # Start looking for appropriate interpolation locations
        fc = f & Q(use_category__grouped_by=c)
        for l in q.filter(fc & Q(floor_area__isnull=True)).all():
            r_degree = 0
            while True:
                # Default Distance is metres, so multiply accordingly
                r = (constants.BOUNDS**r_degree)*1000 # metres
                ql = q.annotate(distance=Distance("pc__point", l.pc.point)) \
                      .filter(fc & Q(floor_area__isnull=False) & Q(distance__lte=r)) \
                      .values("rental_valuation", "floor_area")
                if len(ql) < constants.LOWER_RANGE:
                    if r > constants.UPPER_RADIUS*1000:
                        # Further than the longest possible distance
                        break
                    r_degree += 1
                else:
                    m = median([x["rental_valuation"]/x["floor_area"]
                                for x in ql if x["floor_area"] > 0.0])
                    l.floor_area = l.rental_valuation / m
                    l.save()
                    break

我的问题是这个函数需要6天才能运行。一定有更快的方法,对吧?我肯定我做错了什么.

这些模式如下:

代码语言:javascript
复制
class LocationCategory(models.Model):
    # Category types
    GRP = "GRP"
    SGP = "SGP"
    UST = "UST"
    CATEGORIES = (
        (GRP, "Group"),
        (SGP, "Sub-group"),
        (UST, "Use type"),
    )
    slug = models.CharField(max_length=24, primary_key=True, unique=True)
    usecode = models.CharField(max_length=14, db_index=True)
    use_category = models.CharField(max_length=3, choices=CATEGORIES,
                                    db_index=True, default=UST)
    grouped_by = models.ForeignKey("self", null=True, blank=True,
                                   on_delete=models.SET_NULL,
                                   related_name="category_by_group")

class Location(models.Model):
    # Hereditament identity and location
    slug = models.CharField(max_length=24, db_index=True)
    locode = models.CharField(max_length=14, db_index=True)
    pc = models.ForeignKey(Postcode, null=True, blank=True,
                           on_delete=models.SET_NULL,
                           related_name="locations_by_pc")
    use_category = models.ForeignKey(LocationCategory, null=True, blank=True,
                                     on_delete=models.SET_NULL,
                                     related_name="locations_by_category")
    # History fields
    update_cycle = models.CharField(max_length=14, db_index=True)
    # Location-specific econometric data
    floor_area = models.FloatField(blank=True, null=True)
    rental_valuation = models.FloatField(blank=True, null=True)

class Postcode(models.Model):
    pc = models.CharField(max_length=7, primary_key=True, unique=True) # Postcode excl space
    pcs = models.CharField(max_length=8, unique=True)                  # Postcode incl space
    # http://spatialreference.org/ref/epsg/osgb-1936-british-national-grid/
    point = models.PointField(srid=4326)

使用Django 2.0和Postgresql 10

更新

通过以下代码更改,我在运行时实现了35%的改进:

代码语言:javascript
复制
# Initial query selecting all latest locations, and excluding null rental valuations
q = Location.objects.order_by("slug","-update_cycle") \
                    .distinct("slug")
# Chained Q objects to use in filter
f = Q(rental_valuation__isnull=False) & \
    Q(pc__isnull=False) & \
    Q(use_category__grouped_by_id=category_id)
# All property categories at subgroup level
# Start looking for appropriate interpolation locations
for l in q.filter(f & Q(floor_area__isnull=True)).all().iterator():
    r = q.filter(f & Q(floor_area__isnull=False) & ~Q(floor_area=0.0))
    rl = Location.objects.filter(id__in = r).annotate(distance=D("pc__point", l.pc.point)) \
                                            .order_by("distance")[:constants.LOWER_RANGE] \
                                            .annotate(floor_ratio = F("rental_valuation")/
                                                                    F("floor_area")) \
                                            .values("floor_ratio")
    if len(rl) == constants.LOWER_RANGE:
        m = median([h["floor_ratio"] for h in rl])
        l.floor_area = l.rental_valuation / m
        l.save()

id__in=r效率低下,但在添加和排序新注释时,它似乎是维护distinct查询集的唯一方法。考虑到可以在r查询中返回大约100,000行,在其中应用的任何注释,以及随后的按距离进行排序,都会花费很长的时间。

但是..。在实现Subquery功能时,我遇到了许多问题。我认为AttributeError: 'ResolvedOuterRef' object has no attribute '_output_field_or_none'与注释有关,但我在上面找不到多少。

有关的重组守则是:

代码语言:javascript
复制
rl = Location.objects.filter(id__in = r).annotate(distance=D("pc__point", OuterRef('pc__point'))) \
                                        .order_by("distance")[:constants.LOWER_RANGE] \
                                        .annotate(floor_ratio = F("rental_valuation")/
                                                                F("floor_area")) \
                                        .distinct("floor_ratio")

以及:

代码语言:javascript
复制
l.update(floor_area= F("rental_valuation") / CustomAVG(Subquery(locs),0))

我可以看到,这种方法应该是非常有效的,但正确的做法似乎远远超出了我的技能水平。

EN

回答 1

Stack Overflow用户

发布于 2018-04-05 13:11:13

您可以使用(主要是) Django的内置查询方法来简化您的方法,这些方法是经过优化的。更具体地说,我们将使用:

我们将创建一个自定义聚合类来应用我们的AVG函数(这个极好的答案启发了我们的方法:Django 1.11注释子查询聚合)

代码语言:javascript
复制
class CustomAVG(Subquery):
    template = "(SELECT AVG(area_value) FROM (%(subquery)s))"
    output_field = models.FloatField()

我们将用它来计算以下平均值:

代码语言:javascript
复制
for location in Location.objects.filter(rental_valuation__isnull=True):
    location.update(
        rental_valuation=CustomAVG(
            Subquery(
                Location.objects.filter(
                    pc__point__dwithin=(OuterRef('pc__point'), D(m=1000)),
                    rental_valuation__isnull=False
                ).annotate(area_value=F('rental_valuation')/F('floor_area'))
                .distinct('area_value')
            )
        )
    )

分解以上内容:

  • 我们收集所有没有Locationrental_valuation对象,然后“传递”列表。
  • Subquery:我们从当前位置点选择位于radius=1000m圆圈内的Location对象(随您的喜好而定),并在其上将成本/m2计算(使用F()获取每个对象的rental_valuationfloor_area列的值)作为一个名为area_value的列。为了获得更准确的结果,我们只选择该列的不同值。
  • 我们将CustomAVG应用于Subquery,并更新当前位置rental_valuation
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49570712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档