首页 \ 问答 \ 如何使用Elasticsearch进行搜索(How to use search with Elasticsearch)

如何使用Elasticsearch进行搜索(How to use search with Elasticsearch)

我使用python 2.7.11和djnago 1.10.2。 我创建了产品模型并在我的数据库中保存了1000个产品。(postgrelsql)实际上,我使用了Django elasticsearch,但它不起作用。 其搜索只基于产品名称,我需要如果搜索类别,颜色等,然后​​显示相关的产品。 我试了一下例子。

from haystack import indexes
from product.models import Product

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    product_name = indexes.CharField(model_attr='product_name')
    product_colour = indexes.CharField(model_attr='product_colour')

    def get_model(self):
        return Product

    def index_queryset(self, using=None):
        return self.get_model().objects.all() 

我创建了ProductColour模型并在产品模型中使用了product_colour外键。 如果我搜索product_colour,然后显示所有相关的数据。

遵循一些步骤: -

  • 安装django-haystack。
  • INSTALLED_APPS settings.py文件中添加haystack。
  • 修改settings.py文件。

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
        },
    }
    
  • 在urls.py中添加了网址。

    urlpatterns = patterns('',
        url(r'^/search/?$', MySearchView.as_view(), name='search_view'),
    )
    
  • 产品型号。

    class Product(models.Model):
        product_name = models.CharField(max_length=100)
        product_description = models.TextField(default=None, blank=True, null=True)
        product_colour = models.ManyToManyField(ProductColour, blank=True, default=None)
        .......
        .......
        .......
    
  • search.html。

    <form method="get" action=".">
        <table>
            {{ form.as_table }}
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Search">
                </td>
            </tr>
        </table>
    </form>
    

I using python 2.7.11 and djnago 1.10.2. I created product models and saved 1000 products in my database.(postgrelsql) Actually, I used Django elasticsearch but its not working. its search only base on product name, i required if search category, colour, etc. Then show releated product. I tryed example.

from haystack import indexes
from product.models import Product

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    product_name = indexes.CharField(model_attr='product_name')
    product_colour = indexes.CharField(model_attr='product_colour')

    def get_model(self):
        return Product

    def index_queryset(self, using=None):
        return self.get_model().objects.all() 

I created ProductColour models and used product_colour foreignkey in product moedls. If i search product_colour then display all releated data.

Following some steps :-

  • Install django-haystack.
  • Added haystack in INSTALLED_APPS settings.py file.
  • Modify settings.py file.

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
        },
    }
    
  • Added url in urls.py.

    urlpatterns = patterns('',
        url(r'^/search/?$', MySearchView.as_view(), name='search_view'),
    )
    
  • product model.

    class Product(models.Model):
        product_name = models.CharField(max_length=100)
        product_description = models.TextField(default=None, blank=True, null=True)
        product_colour = models.ManyToManyField(ProductColour, blank=True, default=None)
        .......
        .......
        .......
    
  • search.html.

    <form method="get" action=".">
        <table>
            {{ form.as_table }}
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Search">
                </td>
            </tr>
        </table>
    </form>
    

原文:https://stackoverflow.com/questions/41980467
更新时间:2023-05-07 09:05

最满意答案

不要在表单设计器中手动添加行,而应考虑以编程方式添加它们

Const N As Integer = 50

Dim _lines(N - 1) As LineShape
Dim _numbers(N - 1) As Integer

Private Sub frmLineShapes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: Fill the _numbers array with values.

    For i As Integer = 0 To N - 1
        _lines(i) = New LineShape With { _
           .X1 = 5 * i + 10, .Y1 = 20, _
           .X2 = 5 * i + 10, .Y2 = 60, _
           .BorderColor = DirectCast(IIf(_numbers(i) = 3, Color.Blue, Color.Black), Color) _
        }
    Next
    Me.SuspendLayout()
    Me.ShapeContainer1.Shapes.AddRange(_lines)
    Me.ResumeLayout()
End Sub

现在,您可以在数组中使用这些行,并且可以轻松访问并更改它们。


注意:

Visual Basic PowerPacks的形状不会直接添加到表单中; 相反,它们被添加到形状容器。 您必须在窗体设计器中为窗体添加至少一个形状,以便VB自动将形状容器添加到窗体。 如果没有,你仍然可以通过编程来添加它。

Me.SuspendLayout()
Dim ShapeContainer1 = New ShapeContainer
Me.Controls.Add(ShapeContainer1)
ShapeContainer1.Shapes.AddRange(_lines)
Me.ResumeLayout()

更新

如果您手动添加线条,则仍然可以通过名称来访问线条

For i As Integer = 0 To N - 1
    Dim index As Integer = Me.ShapeContainer1.Shapes.IndexOfKey("LineShape" & (i + 1))
    Dim line As LineShape = DirectCast(Me.ShapeContainer1.Shapes(index), LineShape)
    If _numbers(i) = 3 Then
        line.BorderColor = Color.Blue
    Else
        line.BorderColor = Color.Black
    End If
Next

Instead of adding the lines manually in the forms designer, consider adding them programmatically

Const N As Integer = 50

Dim _lines(N - 1) As LineShape
Dim _numbers(N - 1) As Integer

Private Sub frmLineShapes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: Fill the _numbers array with values.

    For i As Integer = 0 To N - 1
        _lines(i) = New LineShape With { _
           .X1 = 5 * i + 10, .Y1 = 20, _
           .X2 = 5 * i + 10, .Y2 = 60, _
           .BorderColor = DirectCast(IIf(_numbers(i) = 3, Color.Blue, Color.Black), Color) _
        }
    Next
    Me.SuspendLayout()
    Me.ShapeContainer1.Shapes.AddRange(_lines)
    Me.ResumeLayout()
End Sub

Now you have the lines in an array and can access and change them later easily.


NOTE:

The shapes of the Visual Basic PowerPacks are not added to the form directly; instead, they are added to a shape container. You must have added at least one shape to the form in the forms designer for VB to add a shape container automatically to the form. If not, you can still add it programmatically.

Me.SuspendLayout()
Dim ShapeContainer1 = New ShapeContainer
Me.Controls.Add(ShapeContainer1)
ShapeContainer1.Shapes.AddRange(_lines)
Me.ResumeLayout()

UPDATE:

If you add the lines manually, you can still access the lines by their names

For i As Integer = 0 To N - 1
    Dim index As Integer = Me.ShapeContainer1.Shapes.IndexOfKey("LineShape" & (i + 1))
    Dim line As LineShape = DirectCast(Me.ShapeContainer1.Shapes(index), LineShape)
    If _numbers(i) = 3 Then
        line.BorderColor = Color.Blue
    Else
        line.BorderColor = Color.Black
    End If
Next

相关问答

更多
  • vb.net那里下载[2022-12-02]

    官方下载地址:http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express 此为:vb.net express版本,没有时间限制
  • VB.NET(版本10)具有与C#一样的自动属性。 等效的语法如下所示: Public Overridable Property Comments() As ICollection(Of Comment) 自动转换器倾向于产生比所需更冗长的语法。 如果需要,可以扩展它,但除非使用旧版本的编译器,否则它不是必需的。 Private m_Comments As ICollection(Of Comment) Public Overridable Property Comments() As ICollect ...
  • 我编译它并反编译IL; 在C#中是: string eToken = "abc"; // from: Dim eToken As String = "abc" in my code if (!Conversions.ToBoolean(eToken.ToLower())) { throw new Exception("An eToken is required for this kind of VPN-Permission."); } 所以有你的答案:它使用的是Conversions.ToBoo ...
  • 在常规框架中取代它是一种不重要的方法。 避免在调试帮助上耗费太多精力。 一个简单的直接翻译可能是: Debug.Print("{1}{0}{2}{0}{3}{0}{4}", vbTab, "one", 2, "three", 4) It is an untrivial method to replace, nothing close in the regular framework. Avoid burning too much effort on a debugging aid. A simpl ...
  • 您可以使用CodeDom对象执行此类操作。 CodeDom对象允许您在运行时动态生成程序集。 例如,如果您创建一个界面 Public Interface IScript Property Variable1 As String Sub DoWork() End Interface 然后,您创建一个方法,如下所示: Imports Microsoft.VisualBasic Imports System.CodeDom.Compiler ' ... Public Function Gen ...
  • 不要在表单设计器中手动添加行,而应考虑以编程方式添加它们 Const N As Integer = 50 Dim _lines(N - 1) As LineShape Dim _numbers(N - 1) As Integer Private Sub frmLineShapes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'TODO: Fill the _numbers ...
  • 从你之前的问题来看: 我一定会想要一个有吸引力的GUI。 没有什么“Windows”在寻找。 一般来说,这是不好的。 Windows应用应该看起来像Windows应用。 否则地狱会松散: 替代文字http://forum.computerbild.de/attachments/pc-hardware/realtek-hd-audio-manager-front-panel-problem-1470d1205060406-r.jpg 替代文字http://www.techfuels.com/attachmen ...
  • mainTable.WidthPercentage(New Single() {100, 0}, pageSize) mainTable.WidthPercentage(New Single() {100, 0}, pageSize)
  • https://github.com/lextm/sharpsnmplib/tree/master/Samples/VB.NET 所有VB.NET样本都在那里。 同时,任何VB.NET开发人员都应该学习C#恕我直言。 https://github.com/lextudio/sharpsnmplib/tree/master/Samples/VB.NET All VB.NET samples are there. Meanwhile, any VB.NET developer should learn C# I ...
  • RosEx的DevExpress CodeRush (Visual Studio 2015+) DevExpress CodeRush for Roslyn (Visual Studio 2015+)

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)