简体   繁体   English

Elasticsearch-查询字符串或仅查询字符串以及如何

[英]Elasticsearch - query string or simply query string and how

I have a list of cities as array in PHP, let's say ["Munich", "New York", Chicago"]. 我有一个用PHP数组表示的城市列表,比方说[“慕尼黑”,“纽约”,芝加哥“]。

I want to produce a query in elastic search which basically says 我想在弹性搜索中产生一个查询,基本上说

"SELECT * FROM job_ads WHERE city = Munich OR city = New York OR city = Chicago"

What is the best way to do this? 做这个的最好方式是什么?

So far https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html seems the best for this job. 到目前为止, https://www.elastic.co/guide/zh-CN/elasticsearch/reference/current/query-dsl-simple-query-string-query.html似乎是这项工作的最佳选择。 But if it is, I could need some help with the syntax, I'm very new to elasticsearch. 但是,如果是这样,我可能需要一些语法帮助,对于Elasticsearch我还是很陌生。

According the documentation you provided: you need to read the flag part. 根据您提供的文档:您需要阅读标志部分。

{
    "simple_query_string" : {
        "query" : "Munich | New York | Chicago*",
        "flags" : "OR"
    }
}

ie: there is more flags 即:还有更多标志

So, you can create this json in php with json_encode function. 因此,您可以使用json_encode函数在php中创建此json。

Example: 例:

<?php

$source = ['Munich', 'New York', 'Chicago'];

$search = [];
$search['simple_query_string']['query'] = implode(' | ', $source);
$search['simple_query_string']['flags'] = 'OR';

echo json_encode($search); // voila !

?>

The tips is on the usage of a array for the source + implode function 技巧是关于将数组用于source + implode函数

A simple way would be to use query string query like this. 一种简单的方法是使用像这样的查询字符串查询

{
  "query": {
    "query_string": {
      "fields": ["city"],
      "query": "Munich OR \"New York\" OR Chicago"
    }
  }
}

You would have to use \\" for exact phrase match or else you would get results which contains any of those two words. 您必须使用\\“进行精确的词组匹配 ,否则您将获得包含这两个单词中任何一个的结果。

Now if you are in control of the data, best way to write this kind of query would be to use terms filter which can also be cached but you would have to make sure that city field is not analyzed . 现在,如果您可以控制数据,则编写此类查询的最佳方法是使用也可以缓存的 术语过滤器 ,但您必须确保未分析 city字段。 You can read more about implications of analyzed and not analyzed fields here (scroll down to Why doesn't the term query match my document? ) 您可以在此处详细了解已分析和未分析字段的含义(向下滚动至“查询为什么不匹配我的文档?” )。

After that you could use terms query like this 之后,您可以像这样使用条款查询

{
  "query": {
    "terms": {
      "city": [
        "New York",
        "Chicago",
        "Munich"
      ]
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM