次の方法で共有


Dataverse 検索クエリ

クエリ操作は検索語句に基づいて検索結果を返します。

検索語句に加えて、次のパラメーターの値を渡すことで結果に影響を与えることができます。

名前 タイプ Description 詳細情報
search 文字列 必須。 検索するための語句。 検索パラメーター
count ブール値 合計レコード数を返すかどうか。 count パラメーター
entities 文字列 検索範囲をテーブルのサブセットに制限します。 エンティティ パラメーター
facets 文字列 ファセットは、データ結果が取得された後にデータ結果にドリルダウンする機能をサポートします。 ファセット パラメーター
filter 文字列 返される検索結果の範囲を制限します。 フィルター パラメーター
options 文字列 オプションは、検索語句 を検索するように構成された設定です。 options パラメーター
orderby 文字列 結果を優先順に並べる方法を指定します。 orderby パラメーター
skip int スキップする検索結果の数を指定します。 スキップとトップ パラメーター
top int 取得する検索結果の数を指定します。 スキップとトップ パラメーター

Parameters

このセクションには、前の表で紹介したパラメーターの詳細が含まれています。

search パラメーター

型: 文字列
必須: true

search パラメーターには、検索するテキストが含まれます。 これが唯一の必須パラメーターです。 検索語句は 1 文字以上で、100 文字の制限があります。

単純な検索構文

既定では、search パラメーターは、次の表に示す単純な検索構文をサポートします。

機能 説明
ブール演算子 AND 演算子、+ で示されます
OR 演算子、| で示されます
NOT 演算子、- で示されます
優先演算子 検索語句 hotel+(wifi | luxury) は、用語 hotelwifi または luxury (または両方) を含む結果を検索します。
ワイルドカード 末尾のワイルドカードがサポートされています。 たとえば、Alp* は「alpine」を検索します。
完全一致 引用符 " " で囲まれたクエリ。

メモ

検索文字列の一部として検索演算子を使用するには、文字の先頭に円記号 (\) を付けてエスケープします。 エスケープが必要な特殊文字には、次のものがあります: + - & | ! ( ) { } [ ] ^ " ~ * ? : \ /

たとえば、エスケープされた電話番号は次のようになります: \+1\(800\)555\-1234

options パラメーターを使用すると、さまざまな演算子を有効にするルツェルンクエリ構文を有効にすることができます。

count パラメーター

: ブール値
オプション: true

合計レコード数を返すかどうか。 このパラメーターを設定しない場合、Count の応答プロパティは -1 になります。

entities パラメーター

型: 文字列
オプション: true

既定では、検索には、検索が有効になっているすべてのテーブルが含まれます。 特定のサブセットを検索するには、 entities パラメーターを使用します。

エンティティを設定するときに、どの列を返したいか、どの列を検索するかを指定することもできます。 テーブルのフィルター条件を含めることもできます。

環境で有効になっているテーブルのリストを取得するには、Search Status APIを使用し、entitylogicalname 内で entitystatusresults によってリストされているテーブルを探します。

SearchEntity タイプ

この型を使用して、entities パラメーターに渡すテーブルの配列を作成します。

フィールド名 タイプ Description
name 文字列 必須。 テーブルの論理名です。 クエリの範囲を指定します。
selectColumns string[] オプション。 応答でテーブルドキュメントが返されるときに選択する列の一覧。 空の場合、テーブルのプライマリ名のみが返されます。
searchColumns string[] オプション。 クエリのスコープを設定する列のリスト。 空の場合、テーブルのプライマリ名のみが検索されます。
filter 文字列 オプション。 エンティティに適用されるフィルター。

次の例は、上記のスキーマを使用するいくつかの JSON データを示しています。

[
   {
      "name":"account",
      "selectColumns":["name","address1_city"],
      "searchColumns":["name","address1_city"],
      "filter":"modifiedon ge 2018-01-01T00:00:00Z"
   },
   {
      "name":"contact",
      "selectColumns":["fullname","address1_city"],
      "searchColumns":["fullname","address1_city"],
      "filter":"modifiedon ge 2018-01-01T00:00:00Z"
   }
]

このデータを使用するには、文字列をエスケープし、要求の本文で entities パラメーターの値として渡します。

{
    "search": "maria",
    "entities":"[{\"name\":\"account\",\"selectColumns\":[\"name\",\"address1_city\"],\"searchColumns\":[\"name\",\"address1_city\"],\"filter\":\"modifiedon ge 2018-01-01T00:00:00Z\"},{\"name\":\"contact\",\"selectColumns\":[\"fullname\",\"address1_city\"],\"searchColumns\":[\"fullname\",\"address1_city\"],\"filter\":\"modifiedon ge 2018-01-01T00:00:00Z\"}]"
}

facets パラメーター

型: 文字列
オプション: true

ファセットのパラメーターは任意です。 文字列には、カンマ区切りの名前と値のペアとして表現された、ファセットをカスタマイズするためのパラメーターが含まれる場合があります。 ファセットを使用して検索結果をグループ化します。

ファセットの定義

ファセットを文字列の配列として定義します。次に例を示します。

[
"entityname,count:100",
"account:primarycontactid,count:100",
"ownerid,count:100",
"modifiedon,values:2019-04-27T00:00:00|2020-03-27T00:00:00|2020-04-20T00:00:00|2020-04-27T00:00:00",
"createdon,values:2019-04-27T00:00:00|2020-03-27T00:00:00|2020-04-20T00:00:00|2020-04-27T00:00:00"
]

配列内の各項目は、クエリによって返されたデータをグループ化するさまざまな方法を表します。 返されるプロパティごとに、次の表の値を使用して適切なファセットを指定します。

ファセットの種類 Description
count ファセット語句の最大数。 既定値は 10 です。 上限はありません。
sort count-countvalue、または-valueに設定します。 count を使用して count で降順で並べ替えます。 -count を使用して count で昇順で並べ替えます。 value を使用して value で昇順で並べ替えます。 -value を使用して value で降順で並べ替えます。
values ファセット エントリ値の動的なセットを指定するパイプ区切りの数値または Edm.DateTimeOffset 値に設定します。 期待される結果を得るには、値を昇順で連続してリストする必要があります。
interval 数値の場合は 0 より大きい整数の間隔、日付時刻値の場合は分、時、日、週、月、四半期、年。
timeoffset ([+-]hh:mm[+-]hhmm、または [+-]hh) に設定します。 使用する場合は、 timeoffset パラメーターを interval オプションと組み合わせて、 Edm.DateTimeOffset型のフィールドに適用する場合にのみ使用します。 この値は、時間境界を設定する際に考慮される UTC 時間オフセットを指定します。

メモ

同じファセット仕様で countsort を組み合わせることができますが、 intervalvaluesと組み合わせることはできません。 また、 intervalvalues を組み合わせることはできません。

ファセットの定義を含むエスケープ文字列を使用して facets 値を設定します。

{
    "search": "maria",
    "facets": "[\"entityname,count:100\",\"account:primarycontactid,count:100\",\"ownerid,count:100\",\"modifiedon,values:2019-04-27T00:00:00|2020-03-27T00:00:00|2020-04-20T00:00:00|2020-04-27T00:00:00\",\"createdon,values:2019-04-27T00:00:00|2020-03-27T00:00:00|2020-04-20T00:00:00|2020-04-27T00:00:00\"]"    
}

詳細については、以下を参照してください:

filter パラメーター

型: 文字列
オプション: true

フィルターを使用すると、検索結果の範囲が制限されます。 検索結果を改善するためにフィルタ―を使います。 この最上位レベルのフィルターは、 createdonmodifiedonなどの複数のエンティティ間で共通の列をフィルター処理するのに役立ちます。

次の構文を使用してフィルターを適用します: <attribute logical name> <filter>。 テーブルの論理名は、フィルターが適用されるエンティティを指定します。

フィルターは次の演算子を使用します。

Operator Description
比較演算子    
eq 等しい revenue eq 100000
ne 等しくない revenue ne 100000
gt より大きい revenue gt 100000
ge 以上 revenue ge 100000
lt より小さい revenue lt 100000
le 以下 revenue le 100000
論理演算子    
and 論理積 revenue lt 100000 and revenue gt 2000
or 論理和 name eq 'sample' or name eq 'test'
not 論理否定 not name eq 'sample'
グループ演算子    
( ) 優先順位のグループ化 (name eq 'sample') or name eq 'test') and revenue gt 5000

options パラメーター

型: 文字列
オプション: true

オプションは、検索語句を検索するように構成する設定です。 options 値をこれらのオプションのシリアル化 Dictionary<string, string> ("{'querytype': 'lucene', 'searchmode': 'all', 'besteffortsearchenabled': 'true', 'grouprankingenabled': 'true'}" など) に設定します。

次の表は、オプションの一覧です。

回答内容 Description
querytype 値は simple または luceneLucerne クエリ構文 のいずれかです
besteffortsearchenabled 検索要求語句に適切な一致が見つからなかった場合に、インテリジェントなクエリ ワークフローが可能性のある結果のセットを返すようにします。
groupranking 結果がテーブルごとにグループ化されている検索結果ページでの表示用に最適化された応答内の結果のランキングを有効にします。
searchmode all として指定する場合、ドキュメントを一致として考慮するために、検索語の一部またはすべてを一致させる必要があります。 その値を any に設定すると、既定で検索語句内の任意の単語と一致します。

Lucerne クエリ構文

Lucene クエリ構文は、次の機能をサポートしています。

機能 説明
ブール演算子 単純なクエリ構文と比較して、拡張されたセットを提供します。
AND 演算子: AND&&+ で示される
OR 演算子: OR|| で示される
NOT 演算子: NOT! で示される
ワイルドカード 末尾のワイルドカードに加えて、先頭のワイルドカードもサポートします。
末尾のワイルドカード - alp*
行間のワイルドカード - /.*pine/
あいまい検索 最大 2 文字のスペルミスのあるクエリをサポートします。
Uniersty~University を返します
Blue~1glueblues を返します
用語ブースト クエリ内の特定の用語の重みが異なります。
Rock^2 electronic は、rock との一致よりも electronic との一致の方が重要である結果を返します。
近接検索 より文脈的な結果を得るために、用語が互いに x 語以内にある結果を返します。
たとえば、"airport hotel"~5 は、airporthotel が互いに 5 語以内の結果を返すため、空港の近くにあるホテルを見つける可能性が高くなります。
正規表現 (regex) 検索 たとえば、/[mh]otel/motelhotel に一致します。

orderby パラメーター

型: 文字列
オプション: true

orderby パラメーターを使用して既定の順序を上書きします。 既定では、結果は関連性スコア (@search.score) の降順で一覧表示されます。 スコアが同じ結果の場合、順序はランダムになります。 このパラメーターは、クエリ文字列にワイルドカード文字を含むクエリ タイプが lucene である場合にのみ使用できます。

asc (既定の昇順) または desc (降順) で続く列名で構成される各句でなるコンマ区切りの句の一覧を使用します。

複数のテーブルの種類を含む結果セットの場合、orderby の句の一覧はグローバルに適用可能である必要があります (たとえば、modifiedoncreatedon@search.score)。 たとえば、関連性によって (優先順位の順に) ランク付けされた結果を取得し、次に上位にリストされた最新の変更されたレコードを取得するには、次のようにします。

"orderby": ["@search.score desc", "modifiedon desc"]

クエリ要求に特定のテーブルの種類のフィルターが含まれる場合、orderby はオプションでテーブル固有の列を指定できます。

skiptop パラメーター

: 整数
オプション: true

これらのパラメーターを count パラメーター と共に使用して、ページング エクスペリエンスを作成します。

既定で、一度に最大 50 件の結果が返されます。 topを使用して 100 まで上げますが、topを使用して 10 などの小さな結果セットを指定し、skipを使用して、ユーザーが次のページに移動したときに以前に返された結果をバイパスします。

回答

クエリ操作からの応答は、JSON データを含むエスケープ文字列です。

エスケープされていない応答には、次のプロパティを使用する JSON が含まれています。

名前 タイプ Description
Error ErrorDetail Azure Cognitive Search からのエラー情報を提供します。
Value QueryResult[] 一致するレコードのコレクション。
Facets Dictionary<string, FacetResult[]> クエリがファセットを要求する場合は、ファセット値のディクショナリ。
QueryContext QueryContext このプロパティはバックエンド検索に使用されます。 これは今後の機能リリースに含まれ、現在は使用されていません。
Count long 要求本文に "Count": trueが含まれている場合、検索に一致するすべてのドキュメントの数。top と skip は無視されます。

応答の種類

このセクションでは、応答で返されるタイプについて説明します。

ErrorDetail

応答の一部として返された Azure Cognitive Search エラー。

名前 タイプ Description
code 文字列 エラー コード。
message 文字列 エラー メッセージ。
propertybag Dictionary<string, object> その他のエラー情報。

QueryResult

応答 QueryResult プロパティで返された各 Value 項目は、Dataverse のレコードを表します。

名前 タイプ Description
Id 文字列 レコードの一意識別子。
EntityName 文字列 テーブルの論理名です。
ObjectTypeCode int オブジェクトの種類コード
Attributes Dictionary<string, object> 記録属性
Highlights Dictionary<string, string[]> 強調表示。
Score 倍精度浮動小数点 ドキュメント スコア。

FacetResult

特定の範囲内にあるフィールド、または特定の値または間隔を持つフィールドを持つドキュメントの数を報告するファセット クエリの結果。

名前 タイプ Description
count 長い? このファセットによって記述されるバケット内にあるドキュメントの数。
from オブジェクト ファセットの範囲の包括的な下限を示す値、または下限がないことを示す null。
to オブジェクト ファセットの範囲の包括的な上限を示す値、または上限がないことを示す null。
type Value | Range ファセットの種類。
value オブジェクト ファセットの値、または間隔ファセットの場合はその値を含む下限。
optionalvalue オブジェクト ルックアップのファセット中に設定される、ファセットの別の値またはオプションの値。

QueryContext

応答の一部として返されるクエリ コンテキスト。 このプロパティはバックエンド検索に使用されます。 これは今後の機能リリースに含まれ、現在は使用されていません。

名前 タイプ Description
originalquery 文字列 リクエストで指定されたクエリ文字列。
alteredquery 文字列 クエリを実行するために使用する Dataverse 検索のクエリ文字列。 元のクエリ文字列にスペルミスが含まれていた場合、または最適な結果が得られなかった場合、Dataverse 検索では変更されたクエリ文字列が使用されます。
reason string[] クエリの背後にある理由は、Dataverse 検索による決定を変更します。
spellsuggestions string[] ユーザーの意図を表す可能性の高い単語であるスペル修正の提案。 Dataverse がスペル チェックによりクエリ検索を変更した場合にのみ設定されます。

使用例

次の例は、クエリ操作の使用方法を示しています。 これらの例では、2022 年 8 月 15 日以降に作成されたレコードに対して、取引先企業テーブルと取引先担当者テーブルの name 列と fullname 列でそれぞれ検索操作を実行し、createdon フィールドで降順に上位 7 件の結果を並べ替えます。

この例は、GitHub の SDK for .NET 検索操作のサンプル に由来します。 OutputSearchQuery 静的メソッドは、search パラメーターの値を受け入れます。

/// <summary>
/// Demonstrate query API
/// </summary>
/// <param name="service">The authenticated IOrganizationService instance to use.</param>
/// <param name="searchTerm">The term to search for</param>
/// <returns></returns>
static void OutputSearchQuery(IOrganizationService service, string searchTerm)
{
    Console.WriteLine("OutputSearchQuery START\n");

    searchqueryRequest request = new() { 
        search = searchTerm,
        count = true,
        top = 7,
        entities = JsonConvert.SerializeObject(new List<SearchEntity>()
        {
            new SearchEntity()
            {
                Name = "account",
                SelectColumns = new List<string>() { "name", "createdon" },
                SearchColumns = new List<string>() { "name" },
                Filter = "statecode eq 0"
            },
            new SearchEntity()
            {
                Name = "contact",
                SelectColumns = new List<string>() { "fullname", "createdon" },
                SearchColumns = new List<string>() { "fullname" },
                Filter = "statecode eq 0"
            }
        }),
        orderby = JsonConvert.SerializeObject(new List<string>() { "createdon desc" }),
        filter = "createdon gt 2022-08-15"

    };
    
    var searchqueryResponse = (searchqueryResponse)service.Execute(request);

    var queryResults = JsonConvert.DeserializeObject<SearchQueryResults>(searchqueryResponse.response);
  

    Console.WriteLine($"\tCount:{queryResults.Count}");
    Console.WriteLine("\tValue:");
    queryResults.Value.ForEach(result =>
    {

        Console.WriteLine($"\t\tId:{result.Id}");
        Console.WriteLine($"\t\tEntityName:{result.EntityName}");
        Console.WriteLine($"\t\tObjectTypeCode:{result.ObjectTypeCode}");
        Console.WriteLine("\t\tAttributes:");
        foreach (string key in result.Attributes.Keys)
        {
            Console.WriteLine($"\t\t\t{key}:{result.Attributes[key]}");
        }
        Console.WriteLine("\t\tHighlights:");
        foreach (string key in result.Highlights.Keys)
        {
            Console.WriteLine($"\t\t\t{key}:");

            foreach (string value in result.Highlights[key])
            {
                Console.WriteLine($"\t\t\t\t{value}:");
            }
        }
        Console.WriteLine($"\t\tScore:{result.Score}\n");

    });
    Console.WriteLine("OutputSearchQuery END\n");
}

出力

OutputSearchQuery クラスの認証済みインスタンスで メソッドを呼び出し、searchTermを "Contoso" に設定する場合:

OutputSearchQuery(service: serviceClient, searchTerm: "Contoso");

出力は、次のようになります。

OutputSearchQuery START

        Count:1
        Value:
                Id:8b35eda1-ef69-ee11-9ae7-000d3a88a4a2
                EntityName:account
                ObjectTypeCode:0
                Attributes:
                        @search.objecttypecode:1
                        name:Contoso Pharmaceuticals (sample)
                        createdon:10/13/2023 5:41:21 PM
                        createdon@OData.Community.Display.V1.FormattedValue:10/13/2023 5:41 PM
                Highlights:
                        name:
                                {crmhit}Contoso{/crmhit} Pharmaceuticals (sample):
                Score:4.986711

OutputSearchQuery END

サポートするクラス

OutputSearchQuery メソッドは、次のサポートするクラスに基づいて要求を送信し、結果を処理します。

searchqueryRequest クラスおよび searchqueryResponse クラス

Power Platform CLI pac modelbuilder build コマンドを使用して、SDK for .NET 用の早期バインドクラスを生成するの説明に従ってこれらのクラスを生成します。

SearchEntity クラス

このクラスを使用して、 SearchEntity 型 データを作成します。

public sealed class SearchEntity
{
    /// <summary>
    /// Gets or sets the logical name of the table. Specifies scope of the query.
    /// </summary>
    [DataMember(Name = "name", IsRequired = true)]
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the list of columns that needs to be projected when table documents are returned in response. 
    /// If empty, only PrimaryName will be returned.
    /// </summary>
    [DataMember(Name = "selectcolumns")]
    public List<string> SelectColumns { get; set; }

    /// <summary>
    /// Gets or sets the list of columns to scope the query on.
    /// If empty, only PrimaryName will be searched on. 
    /// </summary>
    [DataMember(Name = "searchcolumns")]
    public List<string> SearchColumns { get; set; }

    /// <summary>
    /// Gets or sets the filters applied on the entity.
    /// </summary>
    [DataMember(Name = "filter")]
    public string Filter { get; set; }
}
SearchQueryResults クラス

このクラスを使用して、 searchqueryResponse.response 文字列プロパティから JSON データを逆シリアル化します。

public sealed class SearchQueryResults
{
    /// <summary>
    /// Provides error information from Azure Cognitive search.
    /// </summary>
    public ErrorDetail? Error { get; set; }

    /// <summary>
    /// A collection of matching records.
    /// </summary>
    public List<QueryResult>? Value { get; set; }

    /// <summary>
    /// If facets were requested in the query, a dictionary of facet values.
    /// </summary>
    public Dictionary<string, IList<FacetResult>>? Facets { get; set; }

    /// <summary>
    /// The query context returned as part of response. This property is used for backend search. It is included for future feature releases and is not currently used.
    /// </summary>
    public QueryContext? QueryContext { get; set; }

    /// <summary>
    /// If `"Count": true` is included in the body of the request, the count of all documents that match the search, ignoring top and skip.
    /// </summary>
    public long Count { get; set; }
}
ErrorDetail クラス

このクラスを使用して 、ErrorDetail データを逆シリアル化します。

public sealed class ErrorDetail
{
    /// <summary>
    /// Gets or sets the error code.
    /// </summary>
    [DataMember(Name = "code")]
    public string Code { get; set; }

    /// <summary>
    /// Gets or sets the error message.
    /// </summary>
    [DataMember(Name = "message")]
    public string Message { get; set; }

    /// <summary>
    /// Gets or sets additional error information.
    /// </summary>
    [DataMember(Name = "propertybag")]
    public Dictionary<string, object> PropertyBag { get; set; }
}
QueryResult クラス

このクラスを使用して QueryResult データを逆シリアル化します。

public sealed class QueryResult
{
    /// <summary>
    /// Gets or sets the identifier of the record
    /// </summary>
    public string Id { get; set; }

    /// <summary>
    /// Gets or sets the logical name of the table
    /// </summary>
    public string EntityName { get; set; }

    /// <summary>
    /// Gets or sets the object type code
    /// </summary>
    public int ObjectTypeCode { get; set; }

    /// <summary>
    /// Gets or sets the record attributes
    /// </summary>
    public Dictionary<string, object> Attributes { get; set; }

    /// <summary>
    /// Gets or sets the highlights
    /// </summary>
    public Dictionary<string, string[]> Highlights { get; set; }

    // Gets or sets the document score
    public double Score { get; set; }
}
FacetResult クラス

FacetResult データを逆シリアル化するには、このクラスを使用します。

public sealed class FacetResult
{
    /// <summary>
    /// Gets or sets the count of documents falling within the bucket described by this facet.
    /// </summary>
    [DataMember(Name = "count")]
    public long? Count { get; set; }

    /// <summary>
    /// Gets or sets value indicating the inclusive lower bound of the facet's range, or null to indicate that there is no lower bound.
    /// </summary>
    [DataMember(Name = "from")]
    public object From { get; set; }

    /// <summary>
    /// Gets or sets value indicating the exclusive upper bound of the facet's range, or null to indicate that there is no upper bound.
    /// </summary>
    [DataMember(Name = "to")]
    public object To { get; set; }

    /// <summary>
    /// Gets or sets type of the facet - Value or Range.
    /// </summary>
    [DataMember(Name = "type")]
    public FacetType Type { get; set; }

    /// <summary>
    /// Gets or sets value of the facet, or the inclusive lower bound if it's an interval facet.
    /// </summary>
    [DataMember(Name = "value")]
    public object Value { get; set; }

    /// <summary>
    /// Gets or sets additional/ Optional value of the facet, will be populated while faceting on lookups.
    /// </summary>
    [DataMember(Name = "optionalvalue")]
    public object OptionalValue { get; set; }
}
FacetType クラス

ファセット クエリ結果のタイプを指定します。

public enum FacetType
{
    /// <summary>
    /// The facet counts documents with a particular field value.
    /// </summary>
    [EnumMember(Value = "value")]
    Value = 0,

    /// <summary>
    /// The facet counts documents with a field value in a particular range.
    /// </summary>
    [EnumMember(Value = "range")]
    Range = 1,
}
QueryContext クラス

このクラスを使用して QueryContext データを逆シリアル化します。

public sealed class QueryContext
{
    /// <summary>
    /// Gets or sets the query string as specified in the request.
    /// </summary>
    [DataMember(Name = "originalquery")]
    public string OriginalQuery { get; set; }

    /// <summary>
    /// Gets or sets the query string that Dataverse search used to perform the query. 
    /// Dataverse search uses the altered query string if the original query string contained spelling mistakes or did not yield optimal results.
    /// </summary>
    [DataMember(Name = "alteredquery")]
    public string AlteredQuery { get; set; }

    /// <summary>
    /// Gets or sets the reason behind query alter decision by Dataverse search.
    /// </summary>
    [DataMember(Name = "reason")]
    public List<string> Reason { get; set; }

    /// <summary>
    /// Gets or sets the spell suggestion that are the likely words that represent user's intent. 
    /// This will be populated only when the query was altered by Dataverse search due to spell check.
    /// </summary>
    [DataMember(Name = "spellsuggestions")]
    public List<string> SpellSuggestions { get; set; }
}

参照

Dataverse レコードの検索
Dataverse 検索の提案
Dataverse 検索のオートコンプリート
Dataverse 検索の統計と状態
Dataverse のレガシ検索