【问题标题】:Elasticsearch/Nest - Combining multiple range queries (OIC syntax)Elasticsearch/Nest - 组合多个范围查询(OIC 语法)
【发布时间】:2015-12-18 14:17:10
【问题描述】:

这里是 ES 新手(从 SolrNet 世界过渡,所以我正在寻找具有类似语法的指针)

任何人都可以帮助制定一个可能类似于下面的代码 sn-p 的查询没有 lambda。不幸的是,简单的旧 OI 语法中的示例很少,我一直被卡住....

我将如何制定一组布尔范围查询,在 solrnet 中我会做这样的事情来获取属于某个价格范围的商品:

    List<ISolrQuery> queryList = new List<ISolrQuery>();
    double[] priceList = GetPrices(..) //double array
    for (int i = 1; i <= 10; i++)
    {
        queryList.Add(new solr.Query(new SolrQueryByRange<double>("price", priceList[i] * 0.95, priceList[i] * 1.15));
    }

    var results = _solr.Query(new SolrMultipleCriteriaQuery(queryList), new QueryOptions
    {
        Rows = 50,
        Fields = new[] { "Item", "Created", "Price" },
    });

任何人都可以提供等效的 Elasticsearch/Nest 查询吗?

【问题讨论】:

    标签: elasticsearch nest


    【解决方案1】:

    类似下面的东西

    void Main()
    {
        var client = new ElasticClient(connection: new InMemoryConnection());
    
        // prices from your GetPrices method...
        var prices = new[] { 1d, 2d };
    
        var searchRequest = new SearchRequest<Document>("index", "document")
        {
            Fields = new List<Nest.PropertyPathMarker>{ "Item", "Created", "Price" },
            Size = 50,
            Query = new BoolQuery
            {
                Should = prices.Select(p => new RangeQuery
                {
                    Field = "price",
                    GreaterThanOrEqualTo = (p * 0.95).ToString(),
                    LowerThanOrEqualTo = (p * 1.15).ToString()
                }.ToContainer())
            }.ToContainer()
        };
    
        var result = client.Search<Document>(searchRequest);
    
        Console.WriteLine(Encoding.UTF8.GetString(result.RequestInformation.Request));
    }
    
    public class Document
    {
        public string Item { get; set; }
        public DateTime Created { get; set;}
        public double Price {get; set;}
    }
    

    这会在索引"index" 中搜索"document" 类型(强输入到您的Document POCO),使用bool query 和从价格构造的范围子句- 如果文档的price 字段属于任何一个范围,都将被视为匹配。

    从上面的 NEST 查询得到的查询 DSL 是

    {
      "size": 50,
      "fields": [
        "Item",
        "Created",
        "Price"
      ],
      "query": {
        "bool": {
          "should": [
            {
              "range": {
                "price": {
                  "gte": "0.95",
                  "lte": "1.15"
                }
              }
            },
            {
              "range": {
                "price": {
                  "gte": "1.9",
                  "lte": "2.3"
                }
              }
            }
          ]
        }
      }
    }
    

    【讨论】:

    • 很好的答案。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多