elasticsearch中LessThen遇到的坑

开发中,使用到LessThen-小于某个参数的逻辑查询,如下:

cs 复制代码
/// <summary>
/// 查询状态已发布(状态小于2)的政策要闻分页
/// </summary>
/// <param name="input"></param>
/// <returns></returns>    
public async Task<PagedDto<PageSearchOutput>> GetPageSearchResultAsync(PageSearchInput input)
    {
        var elasticSearchManager = LazyServiceProvider.LazyGetRequiredService<IElasticSearchManager>();
        var searchRequest = new SearchRequest<PageIndex>(Nest.Indices.Parse(PageExtensionConsts.IndexName));
        searchRequest.Sort = new List<ISort> { new FieldSort { Field = Infer.Field<PageIndex>(d => d.CreationTime), Order = SortOrder.Descending } };

        var filterList = new List<QueryContainer>{
            new NumericRangeQuery(){
                Field = Infer.Field<PageIndex>(d => d.Status),
                LessThan = (byte)PageStatus.Revoked //小于2的查询出来
            }
        };

        if (input.IsEmpty())
            searchRequest.Query = new BoolQuery
            {
                Filter = filterList
            };
        else
        {
            var shouldList = new List<QueryContainer>();

            if (!input.QueryText.IsNullOrWhiteSpace())
            {
                var titleMatchQuery = new MatchQuery
                {
                    Field = Infer.Field<PageIndex>(d => d.Title),
                    Query = input.QueryText
                };
                var contentMatchQuery = new MatchQuery
                {
                    Field = Infer.Field<PageIndex>(d => d.Content),
                    Query = input.QueryText
                };
                shouldList.Add(titleMatchQuery);
                shouldList.Add(contentMatchQuery);
                searchRequest.Sort = new List<ISort> { new FieldSort { Field = "_score", Order = SortOrder.Descending } };
            }

            if (!input.Category.IsNullOrWhiteSpace())
            {
                filterList.Add(new TermQuery { Field = Infer.Field<PageIndex>(d => d.Category), Value = input.Category });
            }
            if (input.Province.HasValue)
            {
                filterList.Add(new TermQuery { Field = Infer.Field<PageIndex>(d => d.Province), Value = input.Province });
            }
            if (input.City.HasValue)
            {
                filterList.Add(new TermQuery { Field = Infer.Field<PageIndex>(d => d.City), Value = input.City });
            }
            var query = new BoolQuery
            {
                Should = shouldList,
                Filter = filterList
            };
            if (shouldList.Any())
            {
                query.MinimumShouldMatch = 1;
            }
            searchRequest.Query = query;
        }
        var queryDslJson = elasticSearchManager.GetQueryDslJson(searchRequest);

        var esResponse = await elasticSearchManager.SearchAsync<PageIndex>(
            searchRequest,
            (input.PageIndex - 1) * input.PageSize,
            input.PageSize);
        var pageIndices = esResponse.Documents;

        var ids = pageIndices.Select(i => i.Id).ToList();
        var qtos = await _queryRepository.GetPagesHitsAsync(ids);
        var outputs = pageIndices.Select(i =>
        {
            var areaIds = new List<int>();
            var area = string.Empty;
            areaIds.Add(i.Province);
            if (i.City.HasValue)
                areaIds.Add(i.City.Value);
            if (areaIds.Any())
                area = _queryRepository.GetAreaAsync(areaIds).Result;
            return new PageSearchOutput
            {
                Id = i.Id,
                Title = i.Title,
                Content = i.Content,
                CategoryName = PageCategory.FromValue(i.Category).DisplayName,
                TitlePicture = i.TitlePicture,
                CreationTime = i.CreationTime.ToDateTimeStr(),
                Status = ((PageStatus)i.Status).GetDescription(),
                Area = area,
                Hits = qtos.FirstOrDefault(qto => qto.Id == i.Id)?.Hits
            };
        });
        return new PagedDto<PageSearchOutput>(esResponse.Total, outputs.ToList());
    }

但是通过

var queryDslJson = elasticSearchManager.GetQueryDslJson(searchRequest);

转json得到的内容如下:LessThen后参数内容转义成2.0了,

这是因为LessThen是double?类型的,但是es中保存的2,所以导致查询出来的结果不是预期的,把状态=2的数据也查询出来了

cs 复制代码
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "status": {
              "lt": 2.0
            }
          }
        }
      ]
    }
  },
  "sort": [
    {
      "creationTime": {
        "order": "desc"
      }
    }
  ]
}

所以但是修改成

/// <summary>

/// 查询状态已发布(状态小于2)的政策要闻分页

/// </summary>

/// <param name="input"></param>

/// <returns></returns>

public async Task<PagedDto<PageSearchOutput>> GetPageSearchResultAsync(PageSearchInput input)

{

var elasticSearchManager = LazyServiceProvider.LazyGetRequiredService<IElasticSearchManager>();

var searchRequest = new SearchRequest<PageIndex>(Nest.Indices.Parse(PageExtensionConsts.IndexName));

searchRequest.Sort = new List<ISort> { new FieldSort { Field = Infer.Field<PageIndex>(d => d.CreationTime), Order = SortOrder.Descending } };

var filterList = new List<QueryContainer>{

//new NumericRangeQuery(){

// Field = Infer.Field<PageIndex>(d => d.Status),

// LessThan = (byte)PageStatus.Revoked

//}

new TermQuery { Field = Infer.Field<PageIndex>(d => d.Status), Value = (byte)PageStatus.Published } //使用TermQuery 来实现查询逻辑

};

double? tt = (byte)PageStatus.Revoked;

if (input.IsEmpty())

searchRequest.Query = new BoolQuery

{

Filter = filterList

};

else

{

var shouldList = new List<QueryContainer>();

if (!input.QueryText.IsNullOrWhiteSpace())

{

var titleMatchQuery = new MatchQuery

{

Field = Infer.Field<PageIndex>(d => d.Title),

Query = input.QueryText

};

var contentMatchQuery = new MatchQuery

{

Field = Infer.Field<PageIndex>(d => d.Content),

Query = input.QueryText

};

shouldList.Add(titleMatchQuery);

shouldList.Add(contentMatchQuery);

searchRequest.Sort = new List<ISort> { new FieldSort { Field = "_score", Order = SortOrder.Descending } };

}

if (!input.Category.IsNullOrWhiteSpace())

{

filterList.Add(new TermQuery { Field = Infer.Field<PageIndex>(d => d.Category), Value = input.Category });

}

if (input.Province.HasValue)

{

filterList.Add(new TermQuery { Field = Infer.Field<PageIndex>(d => d.Province), Value = input.Province });

}

if (input.City.HasValue)

{

filterList.Add(new TermQuery { Field = Infer.Field<PageIndex>(d => d.City), Value = input.City });

}

var query = new BoolQuery

{

Should = shouldList,

Filter = filterList

};

if (shouldList.Any())

{

query.MinimumShouldMatch = 1;

}

searchRequest.Query = query;

}

var queryDslJson = elasticSearchManager.GetQueryDslJson(searchRequest);

var esResponse = await elasticSearchManager.SearchAsync<PageIndex>(

searchRequest,

(input.PageIndex - 1) * input.PageSize,

input.PageSize);

var pageIndices = esResponse.Documents;

var ids = pageIndices.Select(i => i.Id).ToList();

var qtos = await _queryRepository.GetPagesHitsAsync(ids);

var outputs = pageIndices.Select(i =>

{

var areaIds = new List<int>();

var area = string.Empty;

areaIds.Add(i.Province);

if (i.City.HasValue)

areaIds.Add(i.City.Value);

if (areaIds.Any())

area = _queryRepository.GetAreaAsync(areaIds).Result;

return new PageSearchOutput

{

Id = i.Id,

Title = i.Title,

Content = i.Content,

CategoryName = PageCategory.FromValue(i.Category).DisplayName,

TitlePicture = i.TitlePicture,

CreationTime = i.CreationTime.ToDateTimeStr(),

Status = ((PageStatus)i.Status).GetDescription(),

Area = area,

Hits = qtos.FirstOrDefault(qto => qto.Id == i.Id)?.Hits

};

});

return new PagedDto<PageSearchOutput>(esResponse.Total, outputs.ToList());

}

相关推荐
小刘鸭!1 小时前
Flink中并行度和slot的关系——任务和任务槽
大数据·flink
LI JS@你猜啊2 小时前
Elasticsearch 集群
大数据·服务器·elasticsearch
筒栗子2 小时前
复习打卡大数据篇——Hadoop HDFS 03
大数据·hadoop·hdfs
SelectDB5 小时前
Apache Doris 创始人:何为“现代化”的数据仓库?
大数据·数据库·云原生
SelectDB5 小时前
飞轮科技荣获中国电信星海大数据最佳合作伙伴奖!
大数据·数据库·数据分析
小刘鸭!6 小时前
Hbase的特点、特性
大数据·数据库·hbase
神奇侠20246 小时前
解决集群Elasticsearch 未授权访问漏洞
elasticsearch
Elastic 中国社区官方博客6 小时前
如何通过 Kafka 将数据导入 Elasticsearch
大数据·数据库·分布式·elasticsearch·搜索引擎·kafka·全文检索
神奇侠20246 小时前
解决单台Elasticsearch 未授权访问漏洞
elasticsearch
nece0016 小时前
elasticsearch 杂记
大数据·elasticsearch·搜索引擎