Blog

Blog

PHODAL

地图移动应用实战 —— 服务端构建

上一篇中我们说到了Django Haystack ElasticSearch 环境准备,接着实战啦~~

官方有一个简单的文档说明空间搜索—— Spatial Search

里面只有SolrElasticSearch是支持的,当然我们也不需要这么复杂的特性。

创建Django app名为nx,目录结构如下

.
|______init__.py
|____api.py
|____models.py
|____search_indexes.py
|____templates
| |____search
| | |____indexes
| | | |____nx
| | | | |____note_text.txt

api.py是后面要用的。

Django Haystack Model创建

而一般的model没有什么区别,除了修改了save方法

from django.contrib import admin

from django.contrib.gis.geos import Point
from django.core import validators
from django.utils.translation import ugettext_lazy as _
from django.db import models
from pygeocoder import Geocoder

class Note(models.Model):
    title = models.CharField("标题", max_length=30, unique=True)
    latitude = models.FloatField(blank=True)
    longitude = models.FloatField(blank=True)

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        results = Geocoder.geocode(self.province + self.city + self.address)
        self.latitude = results[0].coordinates[0]
        self.longitude = results[0].coordinates[1]
        super(Note, self).save(*args, **kwargs)

    def get_location(self):
        return Point(self.longitude, self.latitude)

    def get_location_info(self):
        return self.province + self.city + self.address

admin.site.register(Note)

通过Geocoder.geocode 解析用户输入的地址,为了方便直接后台管理了。

创建search_index

在源码的目录下有一个search_indexes.py的文件就是用于索引用的。

from haystack import indexes
from .models import Note

class NoteIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title')
    location = indexes.LocationField(model_attr='get_location')
    location_info = indexes.CharField(model_attr='get_location_info')

    def get_model(self):
        return Note

与些同时我们还需要在templates/search/indexes/nx/目录中有note_text.txt里面的内容是:

{{ object.title }}
{{ object.get_location }}
{{ object.get_location_info }}

创建数据

migrate数据库

python manage.py migrate

run

python manage.py runserver

接着我们就可以后台创建数据了。 打开: http://127.0.0.1:8000/admin/nx/note/,把除了LatitudeLongitude以外的数据都一填——经纬度是自动生成的。就可以创建数据了。

测试

访问 http://localhost:9200/haystack/_search

或者

curl -XGET http://127.0.0.1:9200/haystack/_search

其他:

服务端代码: https://github.com/phodal/django-elasticsearch

客户端代码: https://github.com/phodal/ionic-elasticsearch

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签