Индекс RavenDB больше не возвращает результаты - PullRequest
0 голосов
/ 28 января 2012

Я пытаюсь применить поиск заказов Айенде от здесь к существующему индексу.

Текущий индекс выглядит так:

public class HomeBlurb_IncludeTotalCosts_Search2 : AbstractIndexCreationTask<MPDocument, HomeBlurb_IncludeTotalCosts_Search2.ReduceResult>
{
    public class ReduceResult
    {
        public string Name { get; set; }
        public string Constituency { get; set; }
        public decimal? AmountPaid { get; set; }
    }

    public HomeBlurb_IncludeTotalCosts_Search2()
    {
        Map = mps => from mp in mps
                        from exp in mp.Expenses
                        select new
                        {
                            mp.Name,
                            mp.Constituency,
                            exp.AmountPaid
                        };

        Reduce = results => from result in results
                            group result by new { result.Name, result.Constituency } into g
                            select new
                            {
                                Name = g.Key.Name,
                                Constituency = g.Key.Constituency,
                                AmountPaid = g.Sum(x => x.AmountPaid)
                            };

        Index(x => x.Name, FieldIndexing.Analyzed);
        Index(x => x.Constituency, FieldIndexing.Analyzed);
    }
}

Этот индекс работаетхорошо.Однако, когда я пытаюсь изменить карту на:

from mp in mps
from exp in mp.Expenses
select new
{
    Query = new object[]{mp.Name,mp.Constituency},
    mp.Name,
    mp.Constituency,
    exp.AmountPaid
};

и уменьшить на

from result in results
group result by new { result.Name, result.Constituency } into g
select new
{
    Query = "",
    Name = g.Key.Name,
    Constituency = g.Key.Constituency,
    AmountPaid = g.Sum(x => x.AmountPaid)
};

, я не получаю результатов при запросе свойства Query.Если я удаляю редукцию, индекс возвращает данные, но он всегда возвращает полную MPDocument, что гораздо больше, чем я должен был реализовать.Есть ли способ использовать технику, описанную в оригинальном посте, которая также использует снижение?

Ответы [ 2 ]

1 голос
/ 30 января 2012

Вы можете использовать это в своей функции уменьшения:

Query = g.Select(x => x.Query).Where(x => x != null).FirstOrDefault()

Чтобы выполнить запрос по этому полю, вам нужно иметь отдельную модель запроса и модель результата. Вот полный пример использования вашего кода:

public class MultiTermFieldInMapReduce
{
    public class MPDocument
    {
        public List<Epense> Expenses { get; set; }
        public string Name { get; set; }
        public string Constituency { get; set; }

        public class Epense
        {
            public decimal? AmountPaid { get; set; }
        }
    }

    public class HomeBlurb_IncludeTotalCosts_Search2 : AbstractIndexCreationTask<MPDocument, HomeBlurb_IncludeTotalCosts_Search2.ReduceResult>
    {
        public class ReduceResult
        {
            public string Name { get; set; }
            public string Constituency { get; set; }
            public decimal? AmountPaid { get; set; }
            public object[] Query { get; set; }
        }

        public class SearchModel
        {
            public string Name { get; set; }
            public string Constituency { get; set; }
            public decimal? AmountPaid { get; set; }
            public string Query { get; set; }
        }

        public HomeBlurb_IncludeTotalCosts_Search2()
        {
            Map = mps => from mp in mps
                         from exp in mp.Expenses
                         select new
                         {
                             mp.Name,
                             mp.Constituency,
                             exp.AmountPaid,
                             Query = new object[]
                             {
                                 mp.Name,
                                 mp.Constituency
                             }
                         };

            Reduce = results => from result in results
                                group result by new { result.Name, result.Constituency } into g
                                select new
                                {
                                    Name = g.Key.Name,
                                    Constituency = g.Key.Constituency,
                                    AmountPaid = g.Sum(x => x.AmountPaid),
                                    Query = g.Select(x => x.Query).Where(x => x != null).FirstOrDefault()
                                };

            Index(x => x.Name, FieldIndexing.Analyzed);
            Index(x => x.Constituency, FieldIndexing.Analyzed);
        }
    }

    [Fact]
    public void Query_returns_results()
    {
        using (var store = new EmbeddableDocumentStore { RunInMemory = true }.Initialize())
        {
            using (var session = store.OpenSession())
            {
                session.Store(new MapReduceError.MPDocument
                {
                    Name = "test1",
                    Expenses = new List<MapReduceError.MPDocument.Epense>
                    {
                        new MapReduceError.MPDocument.Epense {AmountPaid = 5.5m},
                        new MapReduceError.MPDocument.Epense {AmountPaid = 5.5m},
                        new MapReduceError.MPDocument.Epense {AmountPaid = 5.5m},
                        new MapReduceError.MPDocument.Epense {AmountPaid = 5.5m}
                    }
                });

                session.Store(new MapReduceError.MPDocument
                {
                    Name = "test2",
                    Expenses = new List<MapReduceError.MPDocument.Epense>
                    {
                        new MapReduceError.MPDocument.Epense {AmountPaid = 10},
                        new MapReduceError.MPDocument.Epense {AmountPaid = 10},
                        new MapReduceError.MPDocument.Epense {AmountPaid = 10},
                        new MapReduceError.MPDocument.Epense {AmountPaid = 10}
                    }
                });

                session.SaveChanges();
            }

            new HomeBlurb_IncludeTotalCosts_Search2().Execute(store);

            using (var session = store.OpenSession())
            {
                var results =
                    session.Query
                        <HomeBlurb_IncludeTotalCosts_Search2.SearchModel, HomeBlurb_IncludeTotalCosts_Search2>()
                        .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
                        .Where(x => x.Query == "test1")
                        .As<HomeBlurb_IncludeTotalCosts_Search2.ReduceResult>()
                        .ToList();

                Assert.Equal(1, results.Count);
                Assert.Equal(22, results.First().AmountPaid);
            }
        }

    }
}
0 голосов
/ 28 января 2012

Я не думаю, что вам нужен индекс Map / Reduce, чтобы сделать это, вы, кажется, сокращаете только имя MPDocument и группу интересов, которые, я думаю, уникальны для каждого члена парламента.

Я думаю, что вывы хотите использовать TransformResults, чтобы вместо этого вы могли изменить форму вывода, что-то вроде этого:

 TransformResults =
            (database, mps) => from mp in mps
                                 select new 
                                 {
                                     mp.Name,
                                     mp.???
                                     < JUST THE BITS YOU WANT RETURNED >
                                 };

Затем вы сделаете запрос следующим образом:

session.Query<mp>("index name")
        .Where(..)
        .As<MPQueryResult>()
        .ToList()
...