ElasticSearch NEST项查询不返回任何结果 [英] ElasticSearch NEST term query returns no results

查看:317
本文介绍了ElasticSearch NEST项查询不返回任何结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的模式

[ElasticType(Name = "importFile")]
public class ImportFile : DocumentMapping
{
    [ElasticProperty(Store = false, Index = FieldIndexOption.NotAnalyzed)]
    public string FileName { get; set; }

    [ElasticProperty(Store = false, Index = FieldIndexOption.NotAnalyzed)]
    public string GroupId { get; set; }

    [ElasticProperty(Store = false, Index = FieldIndexOption.Analyzed)]
    public string FilePath { get; set; }
}



我这样做了一个NEST查询:

I made a NEST query like this one:

    var res = ElasticClient.Search<ImportFile>(s => s
        .Index(ElasticIndexName)
        .Filter(f =>
            f.Term(t => t.FileName, "Group-1.uhh"))).Documents.ToArray();

并返回零个元素!

我在数据库中查看(使用postman)我可以看到我的文档:

If I peek inside the db (using postman) I can see my documents:

{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 14.069489,
    "hits": [
      {
        "_index": "reviewer-bdd-test-index",
        "_type": "importFile",
        "_id": "AU9kUka2hr5Jg98UXOae",
        "_score": 14.069489,
        "_source": {
          "fileName": "Group-1.uhh",
          "groupId": "0ae1206d0644eabd82ae490e612732df5da2cd141fdee70dc64207f86c96094f",
          "filePath": ""
        }
      },
      {
        "_index": "reviewer-bdd-test-index",
        "_type": "importFile",
        "_id": "AU9kZO25hr5Jg98UXRnk",
        "_score": 14.069489,
        "_source": {
          "fileName": "group-1.uhh",
          "groupId": "0ae1206d0644eabd82ae490e612732df5da2cd141fdee70dc64207f86c96094f",
          "filePath": ""
        }
      }
    ]
  }
}


推荐答案

听起来你可能没有明确地把一个类型映射到索引您的文档,因此Elasticsearch基于它所看到的文档中的字段的默认映射推断了映射。例如,给定以下类型

It sounds like you may not have explicitly put a mapping for the type into the index before indexing your documents, so Elasticsearch has inferred the mapping based on the default mappings for fields in the documents it has seen. As an example, given the following type

[ElasticType(Name = "importFile")]
public class ImportFile
{
    [ElasticProperty(Store = false, Index = FieldIndexOption.NotAnalyzed)]
    public string FileName { get; set; }

    [ElasticProperty(Store = false, Index = FieldIndexOption.NotAnalyzed)]
    public string GroupId { get; set; }

    [ElasticProperty(Store = true, Index = FieldIndexOption.Analyzed)]
    public string FilePath { get; set; }
}

如果我们对一些文档进行索引如下:

if we index some documents as follows

void Main()
{
    var settings = new ConnectionSettings(new Uri("http://localhost:9200"));            
    var client = new ElasticClient(settings);

    client.Index<ImportFile>(
        new ImportFile{
            FileName = "Group-1.uhh",
            FilePath = "",
            GroupId = "0ae1206d0644eabd82ae490e612732df" + 
                      "5da2cd141fdee70dc64207f86c96094"
        },
        index => index
            .Index("reviewer-bdd-test-index")
            .Type("importFile")
            .Refresh());

    client.Index<ImportFile>(
        new ImportFile
        {
            FileName = "group-1.uhh",
            FilePath = "",
            GroupId = "0ae1206d0644eabd82ae490e612732df" + 
                      "5da2cd141fdee70dc64207f86c96094"
        },
        index => index
            .Index("reviewer-bdd-test-index")
            .Type("importFile")
            .Refresh());

    var results = client.Search<ImportFile>(s => s
                .Index("reviewer-bdd-test-index")
                .Type("importFile")
                .Query(q => q
                   .Filtered(fq => fq
                        .Filter(f => f
                            .Term(p => p.FileName, "Group-1.uhh")
                        )
                    )
                )
            );

    Console.WriteLine(string.Format("{0} {1}", results.RequestInformation.RequestMethod, results.RequestInformation.RequestUrl));
    Console.WriteLine(Encoding.UTF8.GetString(results.RequestInformation.Request)); 
    Console.WriteLine("Matching document count: {0}", results.Documents.Count());
}

以下内容在控制台中输出

the following is output in the console

POST http://localhost:9200/reviewer-bdd-test-index/importFile/_search
{
  "query": {
    "filtered": {
      "filter": {
        "term": {
          "fileName": "Group-1.uhh"
        }
      }
    }
  }
}
Matching document count: 0


$ b b

我们没有得到匹配的文件。使用

We get no matching documents. Checking the mapping in Elasticsearch with

curl -XGET "http://localhost:9200/reviewer-bdd-test-index/_mapping"

我们看到类型 importFile

{
   "reviewer-bdd-test-index": {
      "mappings": {
         "importFile": {
            "properties": {
               "fileName": {
                  "type": "string"
               },
               "groupId": {
                  "type": "string"
               }
            }
         }
      }
   }
}

这不是我们期望的; fileName groupId 也应该具有index:not_analyzed filePath 在映射中不均匀。这两个都是因为Elasticsearch根据已经传递的文档推断了映射 - fileName groupId 映射为字符串类型,并且将使用标准分析器进行分析,并且我相信 filePath 尚未映射,因为两个已查看的文档都有一个空字符串值,因此 标准分析器 应用于字段将不会产生任何反转索引的标记,因此该字段不包括在映射中。

which is not what we expect; both fileName and groupId should also have "index": "not_analyzed" and filePath is not even in the mapping. Both of these are because Elasticsearch has inferred the mapping based on the documents it has been passed - fileName and groupId have been mapped as string types and will have undergone analysis with the standard analyzer, and I believe filePath has not been mapped because both seen documents had an empty string value for the field, so the standard analyzer applied to the field would not produce any tokens for the inverted index, hence the field is not included in the mapping.

为了确保事情按预期工作,我们需要在索引任何文档之前向索引添加一个映射。

So, to ensure that things work as expected, we need to add a mapping to the index before indexing any documents

void Main()
{
    var settings = new ConnectionSettings(new Uri("http://localhost:9200"));
    var client = new ElasticClient(settings);

    // Add the mapping for ImportFile to the index
    client.CreateIndex(indexSelector => indexSelector
        .Index("reviewer-bdd-test-index")
        .AddMapping<ImportFile>(mapping => mapping
            .MapFromAttributes()
        )
    );

    // ... Same as above after this point
}

这会导致

POST http://localhost:9200/reviewer-bdd-test-index/importFile/_search
{
  "query": {
    "filtered": {
      "filter": {
        "term": {
          "fileName": "Group-1.uhh"
        }
      }
    }
  }
}
Matching document count: 1

成功!我们有一个匹配的文档。检查Elasticsearch中的映射得到我们期望的结果

Success! We have a matching document. Checking the mapping in Elasticsearch yields what we expect

{
   "reviewer-bdd-test-index": {
      "mappings": {
         "importFile": {
            "properties": {
               "fileName": {
                  "type": "string",
                  "index": "not_analyzed"
               },
               "filePath": {
                  "type": "string",
                  "store": true
               },
               "groupId": {
                  "type": "string",
                  "index": "not_analyzed"
               }
            }
         }
      }
   }
}

此外,属性映射可以替换为流式映射

Additionally, the attribute mapping could be replaced with the fluent mapping instead

var indexResult = client.CreateIndex(indexDescriptor => indexDescriptor
    .Index("reviewer-bdd-test-index")
    .AddMapping<ImportFile>(mapping => mapping
        .Type("importFile")
        .MapFromAttributes()
        .Properties(properties => properties
            .String(s => s
                .Name(file => file.FileName)
                .Store(false)
                .Index(FieldIndexOption.NotAnalyzed))
            .String(s => s
                .Name(file => file.GroupId)
                .Store(false)
                .Index(FieldIndexOption.NotAnalyzed))
            .String(s => s
                .Name(file => file.FilePath)
                .Store(true))
        )
    )
);

此时,属性映射或流畅映射将会完成,但有些事情只能通过流畅的映射实现,例如 multi_fields

Either attribute mapping or fluent mapping will do at this point however, there are some things that can only be achieved with fluent mappings such as multi_fields.

这篇关于ElasticSearch NEST项查询不返回任何结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆