如何针对术语优化此 SharePoint 查询?

How do I optimize this SharePoint query for Terms?

我有一个托管元数据服务,它有一个包含术语集和术语的术语组。

我是 SharePoint 查询的新手,目前正在执行以下操作:

  1. 获取客户​​端上下文
  2. 设置凭据
  3. 更新客户端上下文缓存
  4. 获取分类会话
  5. 获取术语库
  6. 获取术语集
  7. 获取条款

对于上述每个步骤,我都在客户端上下文中加载和执行查询。

  1. 是否有更好的方式来加载和执行查询?
  2. 是否有直接的 LINQ 查询或 CAML 查询可用于在给定术语集的 UID 的情况下获取我需要的术语?

代码:

var siteUrl = ConfigHelper.GetValue("SharepointSiteUrl");
var clientContext = new ClientContext(siteUrl);

clientContext.Credentials = new NetworkCredential(ConfigHelper.GetValue("ServiceAccountLogonName"), ConfigHelper.GetValue("ServiceAccountPassword"));

var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

taxonomySession.UpdateCache();

clientContext.Load(taxonomySession, ts => ts.TermStores);
clientContext.ExecuteQuery();

if (taxonomySession.TermStores.Count == 0)
{
    throw new InvalidOperationException("The Taxonomy Service is offline or missing");
}

var termStore = taxonomySession.TermStores[1];

clientContext.Load(termStore);
clientContext.ExecuteQuery();

var termSet = termStore.GetTermSet(new Guid("f40eeb54-7c87-409d-96c7-75ceed6bff60"));
clientContext.Load(termSet);
clientContext.ExecuteQuery();

var terms = termSet.GetAllTerms();
clientContext.Load(terms);
clientContext.ExecuteQuery();

foreach (var term in terms)
{
    clientContext.Load(term, t => t.Id, t => t.Name);
    clientContext.ExecuteQuery();                
}

如何针对术语优化此 SharePoint 查询?

这样

var taxonomySession = TaxonomySession.GetTaxonomySession(ctx);
taxonomySession.UpdateCache();
TermStore ts = taxonomySession.TermStores.GetById(termStoreId);
TermSet set = ts.GetTermSet(termSetId);
TermCollection terms = set.GetAllTerms();

ctx.Load(terms, t=>t.IncludeWithDefaultProperties(term=>term.Name, term=>term.Id));
ctx.ExecuteQuery();

指定示例的主要问题是向服务器提交了一堆中间请求,因此主要优化是:

  • 消除那些中间请求(参见下面的修改示例)
  • 或者因为 SharePoint CSOM 支持 Request Batching 多客户端 可以使用单个批次从服务器请求对象 仅请求

因为如果您的目标是检索特定术语集的术语,那么可以优化示例,如下所示:

var taxonomySession = TaxonomySession.GetTaxonomySession(ctx);
var termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
var termSet = termStore.GetTermSet(termSetId);
var terms = termSet.GetAllTerms();
ctx.Load(terms, tcol => tcol.Include(t => t.Id,t => t.Name));
ctx.ExecuteQuery();

一些建议

  • 更喜欢TermStoreCollection.GetByNameTermStoreCollection.GetById 通过索引获取 TermStore 的方法 因为在后一种情况下 TermStoreCollection 必须被初始化 第一
  • 使用 TaxonomySession.GetDefaultSiteCollectionTermStore method 如果你 需要获取默认术语库